'use client'
import { useState } from 'react'
import { CheckSquare, Plus, Trash2, GripVertical } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/Skeleton'
import { toast } from 'sonner'

type Category = 'inquilino' | 'garante' | 'propietario' | 'comercial' | 'contrato' | 'firma'

const CATEGORY_LABELS: Record<Category, string> = {
  inquilino: 'Inquilino',
  garante: 'Garante',
  propietario: 'Propietario',
  comercial: 'Comercial',
  contrato: 'Contrato',
  firma: 'Firma',
}

const CATEGORY_COLORS: Record<Category, string> = {
  inquilino: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
  garante: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
  propietario: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
  comercial: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
  contrato: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300',
  firma: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300',
}

interface ChecklistItem {
  id: string
  category: Category
  title: string
}

const INITIAL_ITEMS: ChecklistItem[] = [
  { id: '1', category: 'inquilino', title: 'DNI frente y dorso' },
  { id: '2', category: 'inquilino', title: 'Recibos de sueldo (últimos 3)' },
  { id: '3', category: 'inquilino', title: 'Constancia de CUIL/CUIT' },
  { id: '4', category: 'garante', title: 'DNI frente y dorso' },
  { id: '5', category: 'garante', title: 'Escritura del inmueble' },
  { id: '6', category: 'garante', title: 'Libre deuda municipal' },
  { id: '7', category: 'propietario', title: 'DNI frente y dorso' },
  { id: '8', category: 'propietario', title: 'Escritura / título de propiedad' },
  { id: '9', category: 'comercial', title: 'Reserva firmada' },
  { id: '10', category: 'comercial', title: 'Valor de alquiler acordado' },
  { id: '11', category: 'contrato', title: 'Contrato confeccionado' },
  { id: '12', category: 'contrato', title: 'Revisión legal' },
  { id: '13', category: 'firma', title: 'Firma de todas las partes' },
  { id: '14', category: 'firma', title: 'Entrega de llaves' },
]

export function ChecklistConfig({ loading }: { loading: boolean }) {
  const [items, setItems] = useState<ChecklistItem[]>(INITIAL_ITEMS)
  const [activeCategory, setActiveCategory] = useState<Category>('inquilino')
  const [newTitle, setNewTitle] = useState('')

  const filtered = items.filter(i => i.category === activeCategory)

  const addItem = () => {
    if (!newTitle.trim()) return
    setItems(prev => [...prev, { id: Date.now().toString(), category: activeCategory, title: newTitle }])
    setNewTitle('')
    toast.success('Ítem agregado al checklist')
  }

  const removeItem = (id: string) => {
    setItems(prev => prev.filter(i => i.id !== id))
    toast.success('Ítem eliminado')
  }

  if (loading) return <ChecklistSkeleton />

  return (
    <div className="bg-card border border-border rounded-xl p-6 space-y-4">
      <div className="flex items-center gap-2">
        <CheckSquare size={16} className="text-primary" />
        <h3 className="text-sm font-semibold">Plantillas de Checklist</h3>
      </div>
      <p className="text-xs text-muted-foreground -mt-2">
        Estos ítems se aplican automáticamente al crear una nueva operación.
      </p>

      {/* Category tabs */}
      <div className="flex flex-wrap gap-2">
        {(Object.keys(CATEGORY_LABELS) as Category[]).map(cat => (
          <button
            key={cat}
            onClick={() => setActiveCategory(cat)}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors border ${
              activeCategory === cat
                ? 'bg-primary text-primary-foreground border-primary'
                : 'border-border hover:bg-accent'
            }`}
          >
            {CATEGORY_LABELS[cat]}
            <span className="ml-1.5 opacity-60">{items.filter(i => i.category === cat).length}</span>
          </button>
        ))}
      </div>

      {/* Items list */}
      <div className="space-y-1.5">
        {filtered.map(item => (
          <div key={item.id} className="flex items-center gap-3 p-2.5 rounded-lg border border-border hover:bg-accent/30 group transition-colors">
            <GripVertical size={14} className="text-muted-foreground/30 flex-shrink-0" />
            <span className={`w-2 h-2 rounded-full flex-shrink-0 ${CATEGORY_COLORS[item.category].split(' ')[0].replace('bg-', 'bg-').replace('100', '400')}`} />
            <span className="flex-1 text-sm text-foreground">{item.title}</span>
            <button
              onClick={() => removeItem(item.id)}
              className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-destructive/10 text-destructive/60 hover:text-destructive transition-all"
            >
              <Trash2 size={13} />
            </button>
          </div>
        ))}
        {filtered.length === 0 && (
          <p className="text-sm text-muted-foreground text-center py-4">Sin ítems en esta categoría</p>
        )}
      </div>

      {/* Agregar ítem */}
      <div className="flex gap-2 pt-1">
        <Input
          value={newTitle}
          onChange={e => setNewTitle(e.target.value)}
          placeholder={`Nuevo ítem para ${CATEGORY_LABELS[activeCategory]}...`}
          className="text-sm"
          onKeyDown={e => e.key === 'Enter' && addItem()}
        />
        <Button size="sm" onClick={addItem} className="gap-1.5 flex-shrink-0">
          <Plus size={13} /> Agregar
        </Button>
      </div>
    </div>
  )
}

function ChecklistSkeleton() {
  return (
    <div className="bg-card border border-border rounded-xl p-6 space-y-4">
      <Skeleton className="h-5 w-48" />
      <Skeleton className="h-3 w-80" />
      <div className="flex gap-2">
        {Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-8 w-24 rounded-lg" />)}
      </div>
      {Array.from({ length: 5 }).map((_, i) => (
        <Skeleton key={i} className="h-10 w-full rounded-lg" />
      ))}
    </div>
  )
}
