import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  FolderOpen,
  Plus,
  Search,
  X,
  Pencil,
  Trash2,
  FolderCheck,
  FolderArchive,
  ChevronRight,
  MessageSquare,
  Calendar,
} from 'lucide-react'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import { fascicoliApi, type FascicoloResponse, type FascicoloCreate, type FascicoloUpdate } from '@/api/fascicoli.api'
import { formatDate } from '@/lib/utils'
import { getErrorMessage } from '@/api/client'
import { useAuth } from '@/hooks/useAuth'

// ─── Badge stato ──────────────────────────────────────────────────────────────

function StatoBadge({ stato }: { stato: FascicoloResponse['stato'] }) {
  const config: Record<string, { label: string; className: string; Icon: React.ComponentType<{ className?: string }> }> = {
    aperto: {
      label: 'Aperto',
      className: 'bg-green-100 text-green-800 border border-green-200',
      Icon: FolderOpen,
    },
    chiuso: {
      label: 'Chiuso',
      className: 'bg-gray-100 text-gray-700 border border-gray-200',
      Icon: FolderCheck,
    },
    archiviato: {
      label: 'Archiviato',
      className: 'bg-amber-100 text-amber-800 border border-amber-200',
      Icon: FolderArchive,
    },
  }
  const { label, className, Icon } = config[stato] ?? config.aperto
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${className}`}>
      <Icon className="h-3 w-3" />
      {label}
    </span>
  )
}

// ─── Dialog crea / modifica fascicolo ─────────────────────────────────────────

interface FascicoloDialogProps {
  fascicolo?: FascicoloResponse
  onClose: () => void
}

function FascicoloDialog({ fascicolo, onClose }: FascicoloDialogProps) {
  const queryClient = useQueryClient()
  const isEdit = !!fascicolo

  const [form, setForm] = useState<FascicoloCreate & { stato: 'aperto' | 'chiuso' | 'archiviato' }>({
    titolo: fascicolo?.titolo ?? '',
    numero_pratica: fascicolo?.numero_pratica ?? '',
    stato: fascicolo?.stato ?? 'aperto',
    categoria: fascicolo?.categoria ?? '',
    scadenza: fascicolo?.scadenza ? fascicolo.scadenza.substring(0, 16) : '',
    note: fascicolo?.note ?? '',
  })

  const createMutation = useMutation({
    mutationFn: (data: FascicoloCreate) => fascicoliApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['fascicoli'] })
      toast.success('Fascicolo creato')
      onClose()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: (data: FascicoloUpdate) => fascicoliApi.update(fascicolo!.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['fascicoli'] })
      toast.success('Fascicolo aggiornato')
      onClose()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const isPending = createMutation.isPending || updateMutation.isPending

  const handleSubmit = () => {
    if (!form.titolo.trim()) {
      toast.error('Il titolo e obbligatorio')
      return
    }
    const payload = {
      titolo: form.titolo.trim(),
      numero_pratica: form.numero_pratica?.trim() || null,
      stato: form.stato,
      categoria: form.categoria?.trim() || null,
      scadenza: form.scadenza ? new Date(form.scadenza).toISOString() : null,
      note: form.note?.trim() || null,
    }
    if (isEdit) {
      updateMutation.mutate(payload)
    } else {
      createMutation.mutate(payload)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-background rounded-xl shadow-2xl w-full max-w-lg">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b">
          <h3 className="text-lg font-semibold flex items-center gap-2">
            <FolderOpen className="h-5 w-5 text-primary" />
            {isEdit ? 'Modifica fascicolo' : 'Nuovo fascicolo'}
          </h3>
          <button onClick={onClose} className="p-1 rounded hover:bg-muted">
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Body */}
        <div className="px-5 py-4 space-y-4">
          <div className="space-y-1">
            <Label>Titolo *</Label>
            <Input
              value={form.titolo}
              onChange={(e) => setForm((f) => ({ ...f, titolo: e.target.value }))}
              placeholder="Es. Procedura espropriativa via Roma 12"
              autoFocus
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label>Numero pratica</Label>
              <Input
                value={form.numero_pratica ?? ''}
                onChange={(e) => setForm((f) => ({ ...f, numero_pratica: e.target.value }))}
                placeholder="Es. 2024/0042"
              />
            </div>
            <div className="space-y-1">
              <Label>Stato</Label>
              <select
                value={form.stato}
                onChange={(e) => setForm((f) => ({ ...f, stato: e.target.value as typeof form.stato }))}
                className="w-full h-9 rounded-md border border-input bg-background px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              >
                <option value="aperto">Aperto</option>
                <option value="chiuso">Chiuso</option>
                <option value="archiviato">Archiviato</option>
              </select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label>Categoria</Label>
              <Input
                value={form.categoria ?? ''}
                onChange={(e) => setForm((f) => ({ ...f, categoria: e.target.value }))}
                placeholder="Es. Contenzioso, Contratti..."
              />
            </div>
            <div className="space-y-1">
              <Label>Scadenza</Label>
              <Input
                type="datetime-local"
                value={form.scadenza ?? ''}
                onChange={(e) => setForm((f) => ({ ...f, scadenza: e.target.value }))}
              />
            </div>
          </div>

          <div className="space-y-1">
            <Label>Note</Label>
            <textarea
              value={form.note ?? ''}
              onChange={(e) => setForm((f) => ({ ...f, note: e.target.value }))}
              placeholder="Descrizione, riferimenti normativi..."
              rows={3}
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none"
            />
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-3 px-5 py-4 border-t">
          <Button variant="outline" onClick={onClose}>Annulla</Button>
          <Button onClick={handleSubmit} isLoading={isPending}>
            {isEdit ? 'Salva modifiche' : 'Crea fascicolo'}
          </Button>
        </div>
      </div>
    </div>
  )
}

// ─── Pagina principale ────────────────────────────────────────────────────────

export function FascicoliPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { isAdmin } = useAuth()

  const [search, setSearch] = useState('')
  const [filterStato, setFilterStato] = useState('')
  const [showDialog, setShowDialog] = useState(false)
  const [editFascicolo, setEditFascicolo] = useState<FascicoloResponse | null>(null)
  const [deleteConfirm, setDeleteConfirm] = useState<FascicoloResponse | null>(null)

  const { data: fascicoli = [], isLoading } = useQuery({
    queryKey: ['fascicoli', filterStato, search],
    queryFn: () =>
      fascicoliApi.list({
        stato: filterStato || undefined,
        search: search || undefined,
      }),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => fascicoliApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['fascicoli'] })
      toast.success('Fascicolo eliminato')
      setDeleteConfirm(null)
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b bg-background px-6 py-4 flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold flex items-center gap-2">
            <FolderOpen className="h-5 w-5 text-primary" />
            Fascicoli
          </h1>
          <p className="text-sm text-muted-foreground">
            {fascicoli.length} {fascicoli.length === 1 ? 'fascicolo' : 'fascicoli'}
          </p>
        </div>
        <Button onClick={() => { setEditFascicolo(null); setShowDialog(true) }}>
          <Plus className="h-4 w-4 mr-1" />
          Nuovo fascicolo
        </Button>
      </div>

      {/* Filtri */}
      <div className="border-b bg-background px-6 py-3 flex items-center gap-3">
        <div className="relative flex-1 max-w-xs">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            className="pl-8"
            placeholder="Cerca per titolo, numero pratica..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <select
          value={filterStato}
          onChange={(e) => setFilterStato(e.target.value)}
          className="h-9 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
        >
          <option value="">Tutti gli stati</option>
          <option value="aperto">Aperti</option>
          <option value="chiuso">Chiusi</option>
          <option value="archiviato">Archiviati</option>
        </select>
        {(search || filterStato) && (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => { setSearch(''); setFilterStato('') }}
          >
            <X className="h-4 w-4 mr-1" />
            Pulisci
          </Button>
        )}
      </div>

      {/* Contenuto */}
      <div className="flex-1 overflow-y-auto p-6">
        {isLoading ? (
          <div className="flex justify-center py-12">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          </div>
        ) : fascicoli.length === 0 ? (
          <div className="text-center py-16 text-muted-foreground">
            <FolderOpen className="h-14 w-14 mx-auto mb-4 opacity-20" />
            <p className="text-lg font-medium">Nessun fascicolo trovato</p>
            <p className="text-sm mt-1">
              {search || filterStato
                ? 'Prova a modificare i filtri di ricerca.'
                : 'Crea il primo fascicolo per raggruppare le comunicazioni PEC.'}
            </p>
            {!search && !filterStato && (
              <Button
                className="mt-4"
                onClick={() => { setEditFascicolo(null); setShowDialog(true) }}
              >
                <Plus className="h-4 w-4 mr-1" />
                Crea fascicolo
              </Button>
            )}
          </div>
        ) : (
          <div className="max-w-4xl mx-auto space-y-3">
            {fascicoli.map((f) => (
              <div
                key={f.id}
                className="flex items-center gap-4 p-4 rounded-lg border bg-card hover:shadow-sm transition-shadow cursor-pointer group"
                onClick={() => navigate(`/fascicoli/${f.id}`)}
              >
                {/* Icona stato */}
                <div className="flex-shrink-0">
                  {f.stato === 'aperto' && <FolderOpen className="h-6 w-6 text-green-600" />}
                  {f.stato === 'chiuso' && <FolderCheck className="h-6 w-6 text-gray-500" />}
                  {f.stato === 'archiviato' && <FolderArchive className="h-6 w-6 text-amber-600" />}
                </div>

                {/* Info principale */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <p className="font-semibold truncate">{f.titolo}</p>
                    <StatoBadge stato={f.stato} />
                    {f.numero_pratica && (
                      <span className="text-xs text-muted-foreground font-mono bg-muted px-1.5 py-0.5 rounded">
                        #{f.numero_pratica}
                      </span>
                    )}
                    {f.categoria && (
                      <span className="text-xs text-muted-foreground bg-blue-50 border border-blue-100 px-1.5 py-0.5 rounded">
                        {f.categoria}
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-4 mt-1 text-xs text-muted-foreground">
                    <span className="flex items-center gap-1">
                      <MessageSquare className="h-3 w-3" />
                      {f.message_count} {f.message_count === 1 ? 'messaggio' : 'messaggi'}
                    </span>
                    {f.scadenza && (
                      <span className="flex items-center gap-1 text-amber-600">
                        <Calendar className="h-3 w-3" />
                        Scade: {formatDate(f.scadenza)}
                      </span>
                    )}
                    <span>Aggiornato: {formatDate(f.updated_at)}</span>
                  </div>
                  {f.note && (
                    <p className="text-xs text-muted-foreground italic mt-0.5 truncate">{f.note}</p>
                  )}
                </div>

                {/* Azioni */}
                <div className="flex items-center gap-1 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation()
                      setEditFascicolo(f)
                      setShowDialog(true)
                    }}
                    className="p-1.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
                    title="Modifica"
                  >
                    <Pencil className="h-4 w-4" />
                  </button>
                  {isAdmin && (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation()
                        setDeleteConfirm(f)
                      }}
                      className="p-1.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive"
                      title="Elimina"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  )}
                </div>

                <ChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Dialog crea / modifica */}
      {showDialog && (
        <FascicoloDialog
          fascicolo={editFascicolo ?? undefined}
          onClose={() => { setShowDialog(false); setEditFascicolo(null) }}
        />
      )}

      {/* Dialog conferma eliminazione */}
      {deleteConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-background rounded-xl shadow-2xl p-6 w-full max-w-md space-y-4">
            <h3 className="text-lg font-semibold flex items-center gap-2 text-destructive">
              <Trash2 className="h-5 w-5" />
              Elimina fascicolo
            </h3>
            <p className="text-sm text-muted-foreground">
              Stai per eliminare il fascicolo{' '}
              <strong>{deleteConfirm.titolo}</strong>.
              I messaggi collegati non verranno eliminati.
              Questa operazione non puo essere annullata.
            </p>
            <div className="flex justify-end gap-3 pt-2">
              <Button variant="outline" onClick={() => setDeleteConfirm(null)}>
                Annulla
              </Button>
              <Button
                variant="destructive"
                isLoading={deleteMutation.isPending}
                onClick={() => deleteMutation.mutate(deleteConfirm.id)}
              >
                Elimina
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
