/* eslint-disable react-hooks/set-state-in-effect */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Badge } from '@/views/components/ui/badge';
import { Button } from '@/views/components/ui/button';
import {
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/views/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/views/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/views/components/ui/table';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';

interface ProtocolsTableProps {
  tasks: any[];
  title: string;
  description: string;
}

export function ProtocolsTable({
  tasks,
  title,
  description,
}: ProtocolsTableProps) {
  const [page, setPage] = useState(0);
  const [size, setSize] = useState(10);
  const [loading, setLoading] = useState(false);

  const total = tasks.length;
  const totalPages = Math.ceil(total / size);
  const startIndex = page * size;
  const endIndex = Math.min(startIndex + size, total);

  useEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => {
      setLoading(false);
    }, 500);
    return () => clearTimeout(timer);
  }, [page, size]);

  const protocols = useMemo(() => {
    return tasks.slice(startIndex, endIndex);
  }, [tasks, startIndex, endIndex]);

  function handlePreviousPage() {
    setPage((prev) => Math.max(prev - 1, 0));
  }

  function handleNextPage() {
    setPage((prev) => Math.min(prev + 1, totalPages - 1));
  }

  return (
    <DialogContent className="min-w-7xl max-w-7xl h-full max-h-[90vh] flex flex-col overflow-y-auto">
      <DialogHeader>
        <div className="mb-4">
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </div>
      </DialogHeader>

      <div className="mt-4 h-full flex flex-col">
        <div className="flex justify-between items-center mb-4">
          <h2 className="font-bold">Detalhes dos Protocolos</h2>
          <Badge variant="outline">Total: {total}</Badge>
        </div>

        {protocols.length > 0 ? (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[100px]">Código</TableHead>
                <TableHead>Assunto</TableHead>
                <TableHead className="w-[120px]">Data</TableHead>
                <TableHead>Solicitante</TableHead>
                <TableHead>Local</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {protocols.map((protocol) => (
                <TableRow key={protocol.id}>
                  <TableCell className="font-medium">{protocol.id}</TableCell>
                  <TableCell>{protocol.title}</TableCell>
                  <TableCell>{protocol.date}</TableCell>
                  <TableCell>{protocol.sender}</TableCell>
                  <TableCell>{protocol.location}</TableCell>
                </TableRow>
              ))}
              {protocols.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="h-24 text-center">
                    {loading ? 'Carregando...' : 'Nenhum protocolo encontrado.'}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        ) : (
          <div className="text-center py-4 my-auto text-muted-foreground">
            Nenhuma tarefa encontrada
          </div>
        )}

        <div className="flex items-center justify-between px-2 mt-auto pb-4">
          <div className="flex-1 text-sm text-muted-foreground">
            Mostrando {startIndex + 1} - {endIndex} de {total} tarefas
          </div>
          <div className="flex items-center space-x-6 lg:space-x-8">
            <div className="flex items-center space-x-2">
              <p className="text-sm font-medium">Tarefas por página</p>
              <Select
                value={`${size}`}
                onValueChange={(value) => {
                  const newSize = Number(value);
                  setSize(newSize);
                  const newPage = Math.floor(startIndex / newSize);
                  setPage(newPage);
                }}>
                <SelectTrigger className="h-8 w-[70px]">
                  <SelectValue placeholder={size} />
                </SelectTrigger>
                <SelectContent side="top">
                  {[5, 10, 20, 30, 40, 50].map((pageSize) => (
                    <SelectItem key={pageSize} value={`${pageSize}`}>
                      {pageSize}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                className="h-8 w-8 p-0"
                onClick={handlePreviousPage}
                disabled={page === 0}>
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <div className="text-sm">
                Página {page + 1} de {totalPages || 1}
              </div>
              <Button
                variant="outline"
                className="h-8 w-8 p-0"
                onClick={handleNextPage}
                disabled={page >= totalPages - 1 || totalPages === 0}>
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      </div>
    </DialogContent>
  );
}
