import { useState } from 'react'
import { PlusCircle, Pencil, Trash2, Check, X } from 'lucide-react'
import { v4 as uuidv4 } from 'uuid'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { ScrollArea } from '@/components/ui/scroll-area'
import { useProcessStore } from '@/store/process-store'
import { formatCurrency } from '@/lib/format'
import type { Resource, ResourceType } from '@/domain/types'

const RESOURCE_TYPE_LABELS: Record<ResourceType, string> = {
  role: 'Rol',
  person: 'Persona',
  system: 'Sistema',
  equipment: 'Equipo',
  supply: 'Insumo',
}

const RESOURCE_TYPE_COLORS: Record<ResourceType, string> = {
  role: 'bg-slate-100 text-slate-600',
  person: 'bg-green-100 text-green-700',
  system: 'bg-purple-100 text-purple-700',
  equipment: 'bg-amber-100 text-amber-700',
  supply: 'bg-slate-100 text-slate-700',
}

interface ResourceFormState {
  name: string
  type: ResourceType
  costPerHour: string
}

const EMPTY_FORM: ResourceFormState = { name: '', type: 'role', costPerHour: '' }

export function ResourcesPanel() {
  const { currentProcess, resources, addResource, updateResource, deleteResource } = useProcessStore()
  const [showForm, setShowForm] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [form, setForm] = useState<ResourceFormState>(EMPTY_FORM)

  function startAdd() {
    setForm(EMPTY_FORM)
    setEditingId(null)
    setShowForm(true)
  }

  function startEdit(resource: Resource) {
    setForm({ name: resource.name, type: resource.type, costPerHour: resource.costPerHour.toString() })
    setEditingId(resource.id)
    setShowForm(true)
  }

  function cancelForm() {
    setShowForm(false)
    setEditingId(null)
    setForm(EMPTY_FORM)
  }

  async function handleSubmit() {
    if (!form.name.trim() || !currentProcess) return
    const costPerHour = parseFloat(form.costPerHour) || 0

    if (editingId) {
      const existing = resources.find((r) => r.id === editingId)
      if (!existing) return
      await updateResource({ ...existing, name: form.name.trim(), type: form.type, costPerHour })
    } else {
      const newResource: Resource = {
        id: uuidv4(),
        processId: currentProcess.id,
        name: form.name.trim(),
        type: form.type,
        costPerHour,
      }
      await addResource(newResource)
    }
    cancelForm()
  }

  return (
    <ScrollArea className="h-full">
      <div className="p-4 space-y-4">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs font-medium text-slate-700">Recursos del proceso</p>
            <p className="text-xs text-slate-400">{resources.length} definido{resources.length !== 1 ? 's' : ''}</p>
          </div>
          {!showForm && (
            <Button size="sm" variant="outline" onClick={startAdd} className="h-7 text-xs gap-1">
              <PlusCircle className="h-3.5 w-3.5" />
              Nuevo
            </Button>
          )}
        </div>

        {/* Formulario */}
        {showForm && (
          <div className="border border-primary/20 bg-primary/5 rounded-lg p-3 space-y-3">
            <p className="text-xs font-semibold text-slate-700">{editingId ? 'Editar recurso' : 'Nuevo recurso'}</p>

            <div className="space-y-1.5">
              <Label className="text-xs">Nombre</Label>
              <Input
                autoFocus
                placeholder="ej. Analista Senior"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                className="h-8 text-xs"
              />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs">Tipo</Label>
              <Select value={form.type} onValueChange={(v) => setForm((f) => ({ ...f, type: v as ResourceType }))}>
                <SelectTrigger className="h-8 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {(Object.entries(RESOURCE_TYPE_LABELS) as [ResourceType, string][]).map(([value, label]) => (
                    <SelectItem key={value} value={value} className="text-xs">{label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs">Costo por hora</Label>
              <Input
                type="number"
                min={0}
                step={5}
                placeholder="0.00"
                value={form.costPerHour}
                onChange={(e) => setForm((f) => ({ ...f, costPerHour: e.target.value }))}
                className="h-8 text-xs font-mono"
              />
            </div>

            <div className="flex gap-2">
              <Button size="sm" onClick={handleSubmit} disabled={!form.name.trim()} className="flex-1 h-7 text-xs gap-1">
                <Check className="h-3.5 w-3.5" />
                {editingId ? 'Actualizar' : 'Crear'}
              </Button>
              <Button size="sm" variant="ghost" onClick={cancelForm} className="h-7 text-xs">
                <X className="h-3.5 w-3.5" />
              </Button>
            </div>
          </div>
        )}

        {/* Lista */}
        {resources.length === 0 && !showForm ? (
          <div className="text-center py-8">
            <p className="text-xs text-slate-400 mb-2">Sin recursos definidos</p>
            <p className="text-xs text-slate-300">Los recursos (roles, sistemas, equipos) se asignan a actividades para calcular su costo por hora</p>
          </div>
        ) : (
          <div className="space-y-2">
            {resources.map((resource) => (
              <div
                key={resource.id}
                className="flex items-center justify-between p-3 rounded-lg border border-slate-100 hover:border-slate-200 bg-white group"
              >
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <p className="text-xs font-medium text-slate-800 truncate">{resource.name}</p>
                    <span className={`shrink-0 text-[10px] font-medium px-1.5 py-0.5 rounded-full ${RESOURCE_TYPE_COLORS[resource.type]}`}>
                      {RESOURCE_TYPE_LABELS[resource.type]}
                    </span>
                  </div>
                  <p className="text-xs text-slate-500 font-mono">{formatCurrency(resource.costPerHour)}/hora</p>
                </div>
                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6 text-slate-400 hover:text-slate-600"
                    onClick={() => startEdit(resource)}
                  >
                    <Pencil className="h-3 w-3" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6 text-slate-400 hover:text-destructive"
                    onClick={() => deleteResource(resource.id)}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </ScrollArea>
  )
}
