'use client'
import { useState } from 'react'
import { motion } from 'framer-motion'
import {
  DndContext, DragEndEvent, DragOverEvent, DragOverlay,
  DragStartEvent, PointerSensor, useSensor, useSensors,
} from '@dnd-kit/core'
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { cn } from '@/lib/utils'
import { STATUS_LABELS, STATUS_COLORS, type Operation, type OperationStatus } from '@/types'
import Link from 'next/link'
import { Eye } from 'lucide-react'

const COLUMNS: OperationStatus[] = [
  'consulta_recibida', 'reserva_realizada', 'documentacion_pendiente',
  'documentacion_completa', 'contrato_en_confeccion', 'enviado_propietario',
  'enviado_inquilino', 'correcciones', 'listo_para_firma', 'firmado', 'archivado',
]

const COLUMN_COLORS: Record<OperationStatus, string> = {
  consulta_recibida: 'border-t-slate-400',
  reserva_realizada: 'border-t-blue-400',
  documentacion_pendiente: 'border-t-yellow-400',
  documentacion_completa: 'border-t-cyan-400',
  contrato_en_confeccion: 'border-t-purple-400',
  enviado_propietario: 'border-t-indigo-400',
  enviado_inquilino: 'border-t-violet-400',
  correcciones: 'border-t-orange-400',
  listo_para_firma: 'border-t-emerald-400',
  firmado: 'border-t-green-500',
  archivado: 'border-t-gray-400',
}

const INITIAL_OPS: Operation[] = [
  { id: '1', internal_code: '2026-0015', status: 'contrato_en_confeccion', operation_type: 'nuevo', property_address: 'Av. Corrientes 1234', owner_name: 'García, R.', tenant_name: 'López, M.', sent_to_owner: false, sent_to_tenant: false, created_at: '', updated_at: '' },
  { id: '2', internal_code: '2026-0014', status: 'listo_para_firma', operation_type: 'renovacion', property_address: 'Belgrano 567, 3°B', owner_name: 'Martínez, A.', tenant_name: 'Rodríguez, C.', sent_to_owner: true, sent_to_tenant: true, created_at: '', updated_at: '' },
  { id: '3', internal_code: '2026-0012', status: 'documentacion_pendiente', operation_type: 'nuevo', property_address: 'San Martín 890', owner_name: 'Pérez, L.', tenant_name: 'González, J.', sent_to_owner: false, sent_to_tenant: false, created_at: '', updated_at: '' },
  { id: '4', internal_code: '2026-0011', status: 'enviado_propietario', operation_type: 'renovacion', property_address: 'Rivadavia 2345, PH', owner_name: 'Torres, D.', tenant_name: 'Sánchez, P.', sent_to_owner: true, sent_to_tenant: false, created_at: '', updated_at: '' },
  { id: '5', internal_code: '2026-0010', status: 'firmado', operation_type: 'nuevo', property_address: 'Mitre 456, 2°A', owner_name: 'Ruiz, M.', tenant_name: 'Fernández, L.', sent_to_owner: true, sent_to_tenant: true, created_at: '', updated_at: '' },
  { id: '6', internal_code: '2026-0009', status: 'reserva_realizada', operation_type: 'nuevo', property_address: 'Tucumán 789, 1°C', owner_name: 'Castro, R.', tenant_name: 'Méndez, V.', sent_to_owner: false, sent_to_tenant: false, created_at: '', updated_at: '' },
  { id: '7', internal_code: '2026-0008', status: 'consulta_recibida', operation_type: 'renovacion', property_address: 'Florida 321, PB', owner_name: 'Moreno, P.', tenant_name: 'Silva, E.', sent_to_owner: false, sent_to_tenant: false, created_at: '', updated_at: '' },
]

const PROGRESS_MAP: Record<OperationStatus, number> = {
  consulta_recibida: 5, reserva_realizada: 15, documentacion_pendiente: 25,
  documentacion_completa: 45, contrato_en_confeccion: 60, enviado_propietario: 70,
  enviado_inquilino: 80, correcciones: 75, listo_para_firma: 90, firmado: 100, archivado: 100,
}

function KanbanCard({ op, isDragging }: { op: Operation; isDragging?: boolean }) {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: op.id })
  const style = { transform: CSS.Transform.toString(transform), transition }

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className={cn(
        'bg-card border border-border rounded-lg p-3 cursor-grab active:cursor-grabbing select-none',
        'hover:shadow-md transition-shadow',
        isDragging && 'opacity-50'
      )}
    >
      <div className="flex items-start justify-between gap-2 mb-2">
        <span className="font-mono text-xs text-muted-foreground">{op.internal_code}</span>
        <Link href={`/operaciones/${op.id}`} onClick={e => e.stopPropagation()}>
          <Eye size={13} className="text-muted-foreground hover:text-primary" />
        </Link>
      </div>
      <p className="text-sm font-medium text-foreground leading-tight mb-1">{op.property_address}</p>
      <p className="text-xs text-muted-foreground mb-2">{op.tenant_name}</p>
      <div className="flex items-center gap-2">
        <Progress value={PROGRESS_MAP[op.status]} className="h-1 flex-1" />
        <span className="text-xs text-muted-foreground">{PROGRESS_MAP[op.status]}%</span>
      </div>
    </div>
  )
}

export function KanbanBoard() {
  const [operations, setOperations] = useState<Operation[]>(INITIAL_OPS)
  const [activeId, setActiveId] = useState<string | null>(null)

  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }))

  const byStatus = (status: OperationStatus) => operations.filter(op => op.status === status)

  const handleDragStart = (e: DragStartEvent) => setActiveId(e.active.id as string)

  const handleDragEnd = (e: DragEndEvent) => {
    const { active, over } = e
    setActiveId(null)
    if (!over) return

    const targetStatus = over.id as OperationStatus
    if (COLUMNS.includes(targetStatus)) {
      setOperations(prev =>
        prev.map(op => op.id === active.id ? { ...op, status: targetStatus } : op)
      )
    }
  }

  const activeOp = operations.find(op => op.id === activeId)

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">Tablero Kanban</h2>
          <p className="text-sm text-muted-foreground">Arrastrá las operaciones entre columnas para cambiar su estado</p>
        </div>
      </div>

      <DndContext sensors={sensors} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
        <div className="flex gap-3 overflow-x-auto pb-4" style={{ minHeight: 'calc(100vh - 200px)' }}>
          {COLUMNS.map(status => {
            const items = byStatus(status)
            return (
              <div
                key={status}
                className={cn(
                  'flex-shrink-0 w-60 bg-muted/40 dark:bg-muted/20 rounded-xl border-t-2',
                  COLUMN_COLORS[status]
                )}
              >
                <div className="p-3">
                  <div className="flex items-center justify-between mb-3">
                    <h4 className="text-xs font-semibold text-foreground leading-tight">{STATUS_LABELS[status]}</h4>
                    <span className="text-xs bg-muted text-muted-foreground rounded-full w-5 h-5 flex items-center justify-center">
                      {items.length}
                    </span>
                  </div>
                  <SortableContext
                    id={status}
                    items={items.map(i => i.id)}
                    strategy={verticalListSortingStrategy}
                  >
                    <div className="space-y-2 min-h-[60px]">
                      {items.map(op => (
                        <KanbanCard key={op.id} op={op} isDragging={op.id === activeId} />
                      ))}
                    </div>
                  </SortableContext>
                </div>
              </div>
            )
          })}
        </div>

        <DragOverlay>
          {activeOp && (
            <div className="bg-card border border-primary/50 rounded-lg p-3 shadow-xl rotate-2 w-60">
              <p className="font-mono text-xs text-muted-foreground">{activeOp.internal_code}</p>
              <p className="text-sm font-medium mt-1">{activeOp.property_address}</p>
            </div>
          )}
        </DragOverlay>
      </DndContext>
    </div>
  )
}
