import { useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { CanPerform } from '@/components/auth/CanPerform'
import { PuntosDeVentaTable } from '../components/PuntosDeVentaTable'
import { PuntosDeVentaFilters } from '../components/PuntosDeVentaFilters'
import { MedioInactivoBanner } from '../components/MedioInactivoBanner'
import { usePuntosDeVentaList } from '../hooks/usePuntosDeVenta'
import { useMedio } from '../../medios/hooks/useMedio'

export function PuntosDeVentaListPage() {
  const navigate = useNavigate()

  const [page, setPage] = useState(1)
  const [medioId, setMedioId] = useState<number | undefined>(undefined)
  const [activo, setActivo] = useState<boolean | undefined>(undefined)

  const query = {
    page,
    pageSize: 20,
    ...(medioId !== undefined ? { medioId } : {}),
    ...(activo !== undefined ? { activo } : {}),
  }

  const { data, isLoading } = usePuntosDeVentaList(query)

  // Fetch parent medio only when filtering by a single medioId
  const { data: filteredMedio } = useMedio(medioId ?? 0)
  const medioInactivo = medioId !== undefined && filteredMedio?.activo === false

  const handleMedioIdChange = useCallback((value: number | undefined) => {
    setMedioId(value)
    setPage(1)
  }, [])

  const handleActivoChange = useCallback((value: boolean | undefined) => {
    setActivo(value)
    setPage(1)
  }, [])

  const totalPages = data ? Math.ceil(data.total / (data.pageSize || 20)) : 1
  const hasPrev = page > 1
  const hasNext = page < totalPages

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Puntos de Venta</h1>
        <CanPerform permission="administracion:puntos_de_venta:gestionar">
          <Button
            onClick={() => navigate('/admin/puntos-de-venta/nuevo')}
            size="sm"
            disabled={medioInactivo}
          >
            Nuevo punto de venta
          </Button>
        </CanPerform>
      </div>

      {medioInactivo && filteredMedio && (
        <MedioInactivoBanner medioNombre={filteredMedio.nombre} />
      )}

      <PuntosDeVentaFilters
        onMedioIdChange={handleMedioIdChange}
        onActivoChange={handleActivoChange}
      />

      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-12 w-full rounded-md" />
          ))}
        </div>
      ) : (
        <PuntosDeVentaTable rows={data?.items ?? []} medioInactivo={medioInactivo} />
      )}

      {/* Pagination */}
      <div className="flex items-center justify-between pt-2">
        <span className="text-sm text-muted-foreground">
          {data ? `${data.total} punto${data.total !== 1 ? 's' : ''} de venta` : ''}
        </span>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={!hasPrev}
            onClick={() => setPage((p) => p - 1)}
            aria-label="Anterior"
          >
            Anterior
          </Button>
          <span className="flex items-center px-2 text-sm text-muted-foreground">
            {page} / {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={!hasNext}
            onClick={() => setPage((p) => p + 1)}
            aria-label="Siguiente"
          >
            Siguiente
          </Button>
        </div>
      </div>
    </div>
  )
}
