import { useState } from 'react'
import { AlertCircle, Plus } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
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 { ProductPriceHistory } from '../components/ProductPriceHistory'
import type { ProductListItem, ProductDetail } from '../types'

const PAGE_SIZE = 20

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)

  // ── Prices dialog state (PRD-003) ────────────────────────────────────────
  const [pricesOpen, setPricesOpen] = useState(false)
  const [pricesProductId, setPricesProductId] = useState<number | null>(null)
  const [pricesProductName, setPricesProductName] = useState<string>('')

  // ── Pagination & filter state ────────────────────────────────────────────
  const [page, setPage] = useState(1)
  const [medioIdFilter, setMedioIdFilter] = useState<number | undefined>(undefined)

  const { data: paged, isLoading, isError } = useProducts({
    activo: true,
    page,
    pageSize: PAGE_SIZE,
    medioId: medioIdFilter,
  })
  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)
  }

  function openPrices(p: ProductListItem) {
    setPricesProductId(p.id)
    setPricesProductName(p.nombre)
    setPricesOpen(true)
  }

  async function handleDeactivate(id: number) {
    await deactivateProduct(id)
    toast.success('Producto desactivado')
  }

  function handleMedioFilterChange(e: React.ChangeEvent<HTMLInputElement>) {
    const val = e.target.value
    setPage(1)
    setMedioIdFilter(val ? Number(val) : undefined)
  }

  const totalPages = paged ? Math.ceil(paged.total / PAGE_SIZE) : 1

  // ── 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>

      {/* Filters */}
      <div className="flex items-center gap-3">
        <Input
          type="number"
          min={1}
          placeholder="Filtrar por ID de Medio"
          aria-label="Filtrar por ID de Medio"
          className="w-52"
          onChange={handleMedioFilterChange}
        />
      </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">
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => openPrices(p)}
                        aria-label={`Ver precios de ${p.nombre}`}
                      >
                        Ver precios
                      </Button>
                      <CanPerform permission="catalogo:productos:gestionar">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openEdit(p)}
                        >
                          Editar
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => openDeactivate(p)}
                          disabled={!p.isActive}
                        >
                          Desactivar
                        </Button>
                      </CanPerform>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            aria-label="Página anterior"
          >
            Anterior
          </Button>
          <span className="text-sm text-muted-foreground">
            Página {page} de {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page >= totalPages}
            aria-label="Página siguiente"
          >
            Siguiente
          </Button>
        </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}
        />
      )}

      {/* Prices history dialog (PRD-003) */}
      {pricesProductId !== null && (
        <Dialog open={pricesOpen} onOpenChange={setPricesOpen}>
          <DialogContent className="sm:max-w-2xl">
            <DialogHeader>
              <DialogTitle>Precios — {pricesProductName}</DialogTitle>
            </DialogHeader>
            <ProductPriceHistory productId={pricesProductId} />
          </DialogContent>
        </Dialog>
      )}
    </div>
  )
}
