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 { SeccionesTable } from '../components/SeccionesTable'
import { SeccionesFilters } from '../components/SeccionesFilters'
import { MedioInactivoBanner } from '../components/MedioInactivoBanner'
import { useSeccionesList } from '../hooks/useSeccionesList'
import { useMedio } from '../../medios/hooks/useMedio'
import type { TipoSeccion } from '../types'

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

  const [page, setPage] = useState(1)
  const [medioId, setMedioId] = useState<number | undefined>(undefined)
  const [tipo, setTipo] = useState<TipoSeccion | undefined>(undefined)
  const [activo, setActivo] = useState<boolean | undefined>(undefined)
  const [q, setQ] = useState<string>('')

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

  const { data, isLoading } = useSeccionesList(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 handleTipoChange = useCallback((value: TipoSeccion | undefined) => {
    setTipo(value)
    setPage(1)
  }, [])

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

  const handleSearchChange = useCallback((value: string) => {
    setQ(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">Secciones</h1>
        <CanPerform permission="administracion:secciones:gestionar">
          <Button
            onClick={() => navigate('/admin/secciones/nuevo')}
            size="sm"
            disabled={medioInactivo}
          >
            Nueva sección
          </Button>
        </CanPerform>
      </div>

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

      <SeccionesFilters
        onMedioIdChange={handleMedioIdChange}
        onTipoChange={handleTipoChange}
        onActivoChange={handleActivoChange}
        onSearchChange={handleSearchChange}
      />

      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-12 w-full rounded-md" />
          ))}
        </div>
      ) : (
        <SeccionesTable 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} sección${data.total !== 1 ? 'es' : ''}` : ''}
        </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>
  )
}
