import { useState } from 'react'
import { AlertCircle, Plus } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { CanPerform } from '@/components/auth/CanPerform'
import { useProductTypes } from '../hooks/useProductTypes'
import { useDeactivateProductType } from '../hooks/useDeactivateProductType'
import { ProductTypeFormDialog } from '../components/ProductTypeFormDialog'
import { DeactivateProductTypeDialog } from '../components/DeactivateProductTypeDialog'
import type { ProductTypeListItem, ProductTypeDetail } from '../types'

export function ProductTypesPage() {
  // ── Create dialog state ──────────────────────────────────────────────────
  const [createOpen, setCreateOpen] = useState(false)

  // ── Edit dialog state ────────────────────────────────────────────────────
  const [editOpen, setEditOpen] = useState(false)
  const [editingProductType, setEditingProductType] = useState<ProductTypeDetail | null>(null)

  // ── Deactivate dialog state ──────────────────────────────────────────────
  const [deactivateOpen, setDeactivateOpen] = useState(false)
  const [deactivatingProductType, setDeactivatingProductType] = useState<ProductTypeListItem | null>(null)

  const { data: paged, isLoading, isError } = useProductTypes({ activo: true })
  const { mutateAsync: deactivateProductType } = useDeactivateProductType()

  // ── Handlers ─────────────────────────────────────────────────────────────

  function openCreate() {
    setCreateOpen(true)
  }

  function openEdit(pt: ProductTypeListItem) {
    // Map list item to detail shape for pre-filling (multimedia nulls are fine for list item)
    const detail: ProductTypeDetail = {
      ...pt,
      maxImages: null,
      maxImageSizeMB: null,
      maxImageWidth: null,
      maxImageHeight: null,
      fechaCreacion: '',
      fechaModificacion: null,
    }
    setEditingProductType(detail)
    setEditOpen(true)
  }

  function openDeactivate(pt: ProductTypeListItem) {
    setDeactivatingProductType(pt)
    setDeactivateOpen(true)
  }

  async function handleDeactivate(id: number) {
    await deactivateProductType(id)
    toast.success('Tipo de producto desactivado')
  }

  // ── Loading / Error ───────────────────────────────────────────────────────

  if (isLoading) {
    return (
      <div className="space-y-4 p-4">
        <Skeleton className="h-10 w-48" />
        <Skeleton className="h-64 w-full" />
      </div>
    )
  }

  if (isError) {
    return (
      <Alert variant="destructive" className="m-4">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>Error al cargar tipos de producto.</AlertDescription>
      </Alert>
    )
  }

  const isEmpty = !paged?.items.length

  return (
    <div className="space-y-4 p-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Tipos de Producto</h1>
        <CanPerform permission="catalogo:tipos:gestionar">
          <Button size="sm" onClick={openCreate}>
            <Plus className="mr-2 h-4 w-4" />
            Nuevo Tipo
          </Button>
        </CanPerform>
      </div>

      {isEmpty ? (
        <div className="flex flex-col items-center gap-4 py-16 text-center text-muted-foreground">
          <p>No hay tipos de producto.</p>
          <CanPerform permission="catalogo:tipos:gestionar">
            <Button variant="outline" onClick={openCreate}>
              Crear primer tipo
            </Button>
          </CanPerform>
        </div>
      ) : (
        <div className="rounded-md border">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-muted/50">
                <th className="px-4 py-2 text-left font-medium">Nombre</th>
                <th className="px-4 py-2 text-left font-medium">Duración</th>
                <th className="px-4 py-2 text-left font-medium">Texto</th>
                <th className="px-4 py-2 text-left font-medium">Categoría</th>
                <th className="px-4 py-2 text-left font-medium">Bundle</th>
                <th className="px-4 py-2 text-left font-medium">Imágenes</th>
                <th className="px-4 py-2 text-left font-medium">Activo</th>
                <th className="px-4 py-2" />
              </tr>
            </thead>
            <tbody>
              {paged.items.map((pt: ProductTypeListItem) => (
                <tr key={pt.id} className="border-b last:border-0 hover:bg-muted/25">
                  <td className="px-4 py-2 font-medium">{pt.nombre}</td>
                  <td className="px-4 py-2">{pt.hasDuration ? 'Sí' : 'No'}</td>
                  <td className="px-4 py-2">{pt.requiresText ? 'Sí' : 'No'}</td>
                  <td className="px-4 py-2">{pt.requiresCategory ? 'Sí' : 'No'}</td>
                  <td className="px-4 py-2">{pt.isBundle ? 'Sí' : 'No'}</td>
                  <td className="px-4 py-2">{pt.allowImages ? 'Sí' : 'No'}</td>
                  <td className="px-4 py-2">
                    <span className={pt.isActive ? 'text-green-600' : 'text-red-500'}>
                      {pt.isActive ? 'Activo' : 'Inactivo'}
                    </span>
                  </td>
                  <td className="px-4 py-2">
                    <CanPerform permission="catalogo:tipos:gestionar">
                      <div className="flex gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openEdit(pt)}
                        >
                          Editar
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openDeactivate(pt)}
                          disabled={!pt.isActive}
                        >
                          Desactivar
                        </Button>
                      </div>
                    </CanPerform>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Create dialog */}
      <ProductTypeFormDialog
        open={createOpen}
        onOpenChange={setCreateOpen}
      />

      {/* Edit dialog */}
      {editingProductType && (
        <ProductTypeFormDialog
          open={editOpen}
          onOpenChange={setEditOpen}
          productType={editingProductType}
        />
      )}

      {/* Deactivate confirmation dialog */}
      {deactivatingProductType && (
        <DeactivateProductTypeDialog
          open={deactivateOpen}
          onOpenChange={setDeactivateOpen}
          productType={deactivatingProductType}
          onConfirm={handleDeactivate}
        />
      )}
    </div>
  )
}
