import { useState } from 'react'
import { AlertCircle, ChevronLeft, ChevronRight, Plus } from 'lucide-react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { CanPerform } from '@/components/auth/CanPerform'
import { formatCivilDate, formatCurrency } from '@/lib/formatters'
import { useProductPrices } from '../hooks/useProductPrices'
import { AddProductPriceDialog } from './AddProductPriceDialog'

// ─── Constants ────────────────────────────────────────────────────────────────

const PAGE_SIZE = 20

// ─── Props ────────────────────────────────────────────────────────────────────

interface ProductPriceHistoryProps {
  productId: number
}

// ─── Component ────────────────────────────────────────────────────────────────

export function ProductPriceHistory({ productId }: ProductPriceHistoryProps) {
  const [addOpen, setAddOpen] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)

  const { data: prices, isLoading, isError } = useProductPrices(productId, currentPage, PAGE_SIZE)

  if (isLoading) {
    return (
      <div className="space-y-2">
        <Skeleton className="h-8 w-full" />
        <Skeleton className="h-8 w-full" />
        <Skeleton className="h-8 w-full" />
      </div>
    )
  }

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

  const total = prices?.total ?? 0
  const totalPages = Math.ceil(total / PAGE_SIZE)
  const isEmpty = total === 0

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Historial de precios</h2>
        <CanPerform permission="catalogo:productos:gestionar">
          <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Programar nuevo precio
          </Button>
        </CanPerform>
      </div>

      {isEmpty ? (
        <div className="flex flex-col items-center gap-3 py-12 text-center text-muted-foreground">
          <p>Sin historial de precios. Este producto no tiene precios registrados.</p>
          <CanPerform permission="catalogo:productos:gestionar">
            <Button variant="outline" size="sm" onClick={() => setAddOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Programar nuevo precio
            </Button>
          </CanPerform>
        </div>
      ) : (
        <>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Desde</TableHead>
                  <TableHead>Hasta</TableHead>
                  <TableHead>Precio</TableHead>
                  <TableHead>Estado</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {prices?.items.map((p) => (
                  <TableRow key={p.id}>
                    <TableCell>{formatCivilDate(p.priceValidFrom)}</TableCell>
                    <TableCell>
                      {p.priceValidTo ? formatCivilDate(p.priceValidTo) : '—'}
                    </TableCell>
                    <TableCell>{formatCurrency(p.price)}</TableCell>
                    <TableCell>
                      {p.isActive ? (
                        <Badge variant="default">Vigente</Badge>
                      ) : null}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          <div className="flex items-center justify-between pt-1">
            <span className="text-sm text-muted-foreground">
              Página {currentPage} de {totalPages || 1}
            </span>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                disabled={currentPage <= 1}
                onClick={() => setCurrentPage((p) => p - 1)}
              >
                <ChevronLeft className="h-4 w-4 mr-1" />
                Anterior
              </Button>
              <Button
                variant="outline"
                size="sm"
                disabled={currentPage >= (totalPages || 1)}
                onClick={() => setCurrentPage((p) => p + 1)}
              >
                Siguiente
                <ChevronRight className="h-4 w-4 ml-1" />
              </Button>
            </div>
          </div>
        </>
      )}

      <AddProductPriceDialog
        open={addOpen}
        onOpenChange={setAddOpen}
        productId={productId}
      />
    </div>
  )
}
