import { useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { UsersTable } from '../components/UsersTable'
import { UsersFilters } from '../components/UsersFilters'
import { useUsersList } from '../hooks/useUsersList'
import type { UserListItem } from '../types'

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

  const [page, setPage] = useState(1)
  const [rol, setRol] = useState<string>('')
  const [activo, setActivo] = useState<boolean | undefined>(undefined)
  const [search, setSearch] = useState<string>('')

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

  const { data, isLoading } = useUsersList(query)

  const handleRolChange = useCallback(
    (newRol: string) => {
      setRol(newRol)
      setPage(1)
    },
    [],
  )

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

  const handleSearchChange = useCallback(
    (newSearch: string) => {
      setSearch(newSearch)
      setPage(1)
    },
    [],
  )

  const handleRowClick = useCallback(
    (user: UserListItem) => {
      navigate(`/usuarios/${user.id}/editar`)
    },
    [navigate],
  )

  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">Usuarios</h1>
        <Button onClick={() => navigate('/usuarios/nuevo')} size="sm">
          Nuevo usuario
        </Button>
      </div>

      <UsersFilters
        onRolChange={handleRolChange}
        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>
      ) : (
        <UsersTable rows={data?.items ?? []} onRowClick={handleRowClick} />
      )}

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