'use client'
import { useState } from 'react'
import { motion } from 'framer-motion'
import { Check, ChevronDown, ChevronRight, Upload } from 'lucide-react'
import { Checkbox } from '@/components/ui/checkbox'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'
import { CATEGORY_LABELS, type ChecklistCategory } from '@/types'

const CHECKLIST_DATA: Record<ChecklistCategory, string[]> = {
  inquilino: ['DNI frente', 'DNI dorso', 'Constancia de CUIL', 'Recibo de sueldo', 'Certificación de ingresos', 'Referencias laborales', 'Referencias personales', 'Comprobante de domicilio'],
  garante: ['DNI frente', 'DNI dorso', 'Título de propiedad', 'Informe de dominio', 'Informe de inhibición', 'Recibo de sueldo', 'Garantía aprobada'],
  propietario: ['DNI', 'Escritura', 'CBU', 'Datos fiscales', 'Contrato de administración'],
  comercial: ['Reserva recibida', 'Transferencia recibida', 'Transferencia verificada', 'Comisión abonada', 'Gastos administrativos abonados', 'Inventario realizado', 'Estado de inmueble registrado'],
  contrato: ['Datos cargados', 'Contrato redactado', 'Contrato revisado', 'Contrato aprobado internamente', 'Contrato enviado al propietario', 'Correcciones realizadas (propietario)', 'Aprobado por propietario', 'Contrato enviado al inquilino', 'Correcciones realizadas (inquilino)', 'Aprobado por inquilino'],
  firma: ['Fecha asignada', 'Firma propietario', 'Firma inquilino', 'Firma garantes', 'Entrega de llaves', 'Contrato archivado'],
}

const CATEGORY_COLORS: Record<ChecklistCategory, string> = {
  inquilino: 'border-blue-300 dark:border-blue-700',
  garante: 'border-purple-300 dark:border-purple-700',
  propietario: 'border-green-300 dark:border-green-700',
  comercial: 'border-yellow-300 dark:border-yellow-700',
  contrato: 'border-indigo-300 dark:border-indigo-700',
  firma: 'border-emerald-300 dark:border-emerald-700',
}

function ChecklistGroup({ category, items, checked, onToggle }: {
  category: ChecklistCategory
  items: string[]
  checked: Set<string>
  onToggle: (key: string) => void
}) {
  const [open, setOpen] = useState(true)
  const completedCount = items.filter(i => checked.has(`${category}:${i}`)).length
  const pct = Math.round((completedCount / items.length) * 100)

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      className={cn('bg-card border border-border rounded-xl overflow-hidden border-l-4', CATEGORY_COLORS[category])}
    >
      <button
        onClick={() => setOpen(!open)}
        className="w-full flex items-center justify-between p-4 hover:bg-accent/50 transition-colors"
      >
        <div className="flex items-center gap-3">
          {open ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
          <span className="text-sm font-semibold text-foreground">{CATEGORY_LABELS[category]}</span>
          <Badge variant="outline" className="text-xs">
            {completedCount}/{items.length}
          </Badge>
        </div>
        <div className="flex items-center gap-3">
          <div className="w-24 hidden sm:block">
            <Progress value={pct} className="h-1.5" />
          </div>
          <span className={cn('text-xs font-semibold', pct === 100 ? 'text-green-500' : pct > 50 ? 'text-blue-500' : 'text-yellow-500')}>
            {pct}%
          </span>
        </div>
      </button>

      {open && (
        <div className="border-t border-border divide-y divide-border">
          {items.map(item => {
            const key = `${category}:${item}`
            const isChecked = checked.has(key)
            return (
              <div
                key={key}
                className={cn('flex items-center gap-3 px-4 py-3 transition-colors', isChecked && 'bg-green-50/50 dark:bg-green-900/5')}
              >
                <Checkbox
                  id={key}
                  checked={isChecked}
                  onCheckedChange={() => onToggle(key)}
                />
                <label
                  htmlFor={key}
                  className={cn('flex-1 text-sm cursor-pointer', isChecked && 'line-through text-muted-foreground')}
                >
                  {item}
                </label>
                {isChecked && <Check size={14} className="text-green-500" />}
              </div>
            )
          })}
        </div>
      )}
    </motion.div>
  )
}

export function ChecklistSection({ operationId }: { operationId: string }) {
  const [checked, setChecked] = useState<Set<string>>(new Set([
    'inquilino:DNI frente', 'inquilino:DNI dorso', 'inquilino:Constancia de CUIL',
    'propietario:DNI', 'propietario:Escritura',
    'comercial:Reserva recibida', 'comercial:Transferencia recibida', 'comercial:Transferencia verificada',
    'contrato:Datos cargados', 'contrato:Contrato redactado',
  ]))

  const toggle = (key: string) => {
    setChecked(prev => {
      const next = new Set(prev)
      if (next.has(key)) next.delete(key)
      else next.add(key)
      return next
    })
  }

  const total = Object.values(CHECKLIST_DATA).flat().length
  const done = checked.size
  const totalPct = Math.round((done / total) * 100)

  return (
    <div className="space-y-4">
      <div className="bg-card border border-border rounded-xl p-4 flex items-center gap-4">
        <div className="flex-1">
          <p className="text-sm font-semibold text-foreground mb-1">Progreso Total del Checklist</p>
          <Progress value={totalPct} className="h-2" />
        </div>
        <span className="text-2xl font-bold text-primary">{totalPct}%</span>
        <span className="text-sm text-muted-foreground">{done}/{total} ítems</span>
      </div>

      <div className="space-y-3">
        {(Object.keys(CHECKLIST_DATA) as ChecklistCategory[]).map(cat => (
          <ChecklistGroup
            key={cat}
            category={cat}
            items={CHECKLIST_DATA[cat]}
            checked={checked}
            onToggle={toggle}
          />
        ))}
      </div>
    </div>
  )
}
