import { useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { CanPerform } from '@/components/auth/CanPerform'
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { MediosTable } from '../components/MediosTable'
import { useMediosList } from '../hooks/useMediosList'
import { TIPO_MEDIO_OPTIONS } from '../tipoMedio'

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

  const [page, setPage] = useState(1)
  const [tipo, setTipo] = useState<number | undefined>(undefined)
  const [activo, setActivo] = useState<boolean | undefined>(undefined)
  const [searchRaw, setSearchRaw] = useState('')
  const q = useDebouncedValue(searchRaw, 300)

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

  const { data, isLoading } = useMediosList(query)

  const handleTipoChange = useCallback((value: string) => {
    setTipo(value === '' ? undefined : Number(value))
    setPage(1)
  }, [])

  const handleActivoChange = useCallback((value: string) => {
    if (value === '') setActivo(undefined)
    else setActivo(value === 'true')
    setPage(1)
  }, [])

  const handleSearchChange = useCallback((value: string) => {
    setSearchRaw(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">Medios</h1>
        <CanPerform permission="administracion:medios:gestionar">
          <Button onClick={() => navigate('/admin/medios/nuevo')} size="sm">
            Nuevo medio
          </Button>
        </CanPerform>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 items-center">
        <Input
          type="text"
          placeholder="Buscar por código, nombre..."
          value={searchRaw}
          onChange={(e) => handleSearchChange(e.target.value)}
          className="max-w-xs"
          aria-label="Buscar medios"
        />

        <Select
          value={tipo !== undefined ? String(tipo) : '__all__'}
          onValueChange={(v) => handleTipoChange(v === '__all__' ? '' : v)}
        >
          <SelectTrigger className="h-9 w-40" aria-label="Tipo">
            <SelectValue placeholder="Todos los tipos" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="__all__">Todos los tipos</SelectItem>
            {TIPO_MEDIO_OPTIONS.map((o) => (
              <SelectItem key={o.value} value={String(o.value)}>
                {o.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select
          value={activo !== undefined ? String(activo) : '__all__'}
          onValueChange={(v) => handleActivoChange(v === '__all__' ? '' : v)}
        >
          <SelectTrigger className="h-9 w-32" aria-label="Estado">
            <SelectValue placeholder="Todos" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="__all__">Todos</SelectItem>
            <SelectItem value="true">Activos</SelectItem>
            <SelectItem value="false">Inactivos</SelectItem>
          </SelectContent>
        </Select>
      </div>

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

      {/* Pagination */}
      <div className="flex items-center justify-between pt-2">
        <span className="text-sm text-muted-foreground">
          {data ? `${data.total} medio${data.total !== 1 ? 's' : ''}` : ''}
        </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>
  )
}
