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 { useProducts } from '../hooks/useProducts'
import { useDeactivateProduct } from '../hooks/useDeactivateProduct'
import { ProductFormDialog } from '../components/ProductFormDialog'
import { DeactivateProductDialog } from '../components/DeactivateProductDialog'
import type { ProductListItem, ProductDetail } from '../types'

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

  // ── Edit dialog state ────────────────────────────────────────────────────
  const [editOpen, setEditOpen] = useState(false)
  const [editingProduct, setEditingProduct] = useState<ProductDetail | null>(null)

  // ── Deactivate dialog state ──────────────────────────────────────────────
  const [deactivateOpen, setDeactivateOpen] = useState(false)
  const [deactivatingProduct, setDeactivatingProduct] = useState<ProductListItem | null>(null)

  const { data: paged, isLoading, isError } = useProducts({ activo: true })
  const { mutateAsync: deactivateProduct } = useDeactivateProduct()

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

  function openCreate() {
    setCreateOpen(true)
  }

  function openEdit(p: ProductListItem) {
    const detail: ProductDetail = {
      ...p,
      fechaCreacion: '',
      fechaModificacion: null,
    }
    setEditingProduct(detail)
    setEditOpen(true)
  }

  function openDeactivate(p: ProductListItem) {
    setDeactivatingProduct(p)
    setDeactivateOpen(true)
  }

  async function handleDeactivate(id: number) {
    await deactivateProduct(id)
    toast.success('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 productos.</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">Productos</h1>
        <CanPerform permission="catalogo:productos:gestionar">
          <Button size="sm" onClick={openCreate}>
            <Plus className="mr-2 h-4 w-4" />
            Nuevo Producto
          </Button>
        </CanPerform>
      </div>

      {isEmpty ? (
        <div className="flex flex-col items-center gap-4 py-16 text-center text-muted-foreground">
          <p>No hay productos.</p>
          <CanPerform permission="catalogo:productos:gestionar">
            <Button variant="outline" onClick={openCreate}>
              Crear primer producto
            </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">Medio</th>
                <th className="px-4 py-2 text-left font-medium">Tipo</th>
                <th className="px-4 py-2 text-left font-medium">Precio base</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((p: ProductListItem) => (
                <tr key={p.id} className="border-b last:border-0 hover:bg-muted/25">
                  <td className="px-4 py-2 font-medium">{p.nombre}</td>
                  <td className="px-4 py-2">{p.medioId}</td>
                  <td className="px-4 py-2">{p.productTypeId}</td>
                  <td className="px-4 py-2">{p.basePrice}</td>
                  <td className="px-4 py-2">
                    <span className={p.isActive ? 'text-green-600' : 'text-red-500'}>
                      {p.isActive ? 'Activo' : 'Inactivo'}
                    </span>
                  </td>
                  <td className="px-4 py-2">
                    <CanPerform permission="catalogo:productos:gestionar">
                      <div className="flex gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openEdit(p)}
                        >
                          Editar
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openDeactivate(p)}
                          disabled={!p.isActive}
                        >
                          Desactivar
                        </Button>
                      </div>
                    </CanPerform>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

      {/* Edit dialog */}
      {editingProduct && (
        <ProductFormDialog
          open={editOpen}
          onOpenChange={setEditOpen}
          product={editingProduct}
        />
      )}

      {/* Deactivate confirmation dialog */}
      {deactivatingProduct && (
        <DeactivateProductDialog
          open={deactivateOpen}
          onOpenChange={setDeactivateOpen}
          product={deactivatingProduct}
          onConfirm={handleDeactivate}
        />
      )}
    </div>
  )
}
