import { useState, useEffect } from "react";
import { Search, FileText } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { agentService, OpinionRecord } from "@/services/agent";
import { useToast } from "@/hooks/use-toast";

interface AgentSearchProps {
  onSelectOpinion: (opinion: OpinionRecord) => void;
}

export const AgentSearch = ({ onSelectOpinion }: AgentSearchProps) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [searchResults, setSearchResults] = useState<OpinionRecord[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();

  // Busca pareceres da API
  const handleSearch = async () => {
    setIsLoading(true);
    try {
      const data = await agentService.getOpinions({
        page: currentPage,
        per_page: itemsPerPage,
        search: searchTerm,
      });
      setSearchResults(data);
    } catch (error: any) {
      console.error('Erro ao buscar pareceres:', error);
      toast({
        title: "Erro ao buscar pareceres",
        description: error.message || "Não foi possível buscar os pareceres.",
        variant: "destructive",
      });
      setSearchResults([]);
    } finally {
      setIsLoading(false);
    }
  };

  // Busca automaticamente quando a página ou itemsPerPage mudam
  useEffect(() => {
    if (searchTerm.trim()) {
      handleSearch();
    }
  }, [currentPage, itemsPerPage]);

  // Debounce para busca automática
  useEffect(() => {
    if (!searchTerm.trim()) {
      setSearchResults([]);
      return;
    }

    const timer = setTimeout(() => {
      if (currentPage === 1) {
        handleSearch();
      } else {
        setCurrentPage(1); // Volta para primeira página ao buscar
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const totalPages = Math.ceil(searchResults.length / itemsPerPage);

  return (
    <div className="flex flex-col h-full bg-background">
      <div className="p-6 border-b border-border space-y-4">
        <h2 className="text-2xl font-bold text-foreground">Pesquisar Base de Pareceres</h2>
        <div className="flex gap-2">
          <Input
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Digite título ou categoria..."
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
          />
          <Button onClick={handleSearch} className="gap-2" disabled={isLoading}>
            <Search className="w-4 h-4" />
            {isLoading ? 'Buscando...' : 'Buscar'}
          </Button>
        </div>
        {searchResults.length > 0 && (
          <p className="text-sm text-muted-foreground">
            {searchResults.length} {searchResults.length === 1 ? 'parecer encontrado' : 'pareceres encontrados'}
          </p>
        )}
      </div>

      <div className="flex-1 flex flex-col">
        <ScrollArea className="flex-1 p-6">
          {isLoading ? (
            <div className="text-center text-muted-foreground py-12">
              <p>Buscando pareceres...</p>
            </div>
          ) : searchResults.length > 0 ? (
            <div className="space-y-3">
              {searchResults.map((opinion) => (
                <div
                  key={opinion.id}
                  className="p-4 border border-border rounded-lg hover:bg-accent/50 cursor-pointer transition-colors"
                  onClick={() => onSelectOpinion(opinion)}
                >
                  <div className="flex items-start gap-3">
                    <FileText className="w-5 h-5 text-primary mt-1" />
                    <div className="flex-1">
                      <h3 className="font-semibold text-foreground">{opinion.titulo}</h3>
                      <div className="flex gap-4 mt-2 text-sm text-muted-foreground">
                        <span>{opinion.categoria || '-'}</span>
                        <span>{new Date(opinion.created_at).toLocaleDateString('pt-BR')}</span>
                      </div>
                      <p className="text-sm text-muted-foreground mt-2 line-clamp-2">
                        {opinion.instrucoes}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : searchTerm ? (
            <div className="text-center text-muted-foreground py-12">
              <p>Nenhum parecer encontrado para "{searchTerm}"</p>
            </div>
          ) : (
            <div className="text-center text-muted-foreground py-12">
              <p>Digite um termo para pesquisar na base de pareceres</p>
            </div>
          )}
        </ScrollArea>

        {searchResults.length > 0 && (
          <div className="p-4 border-t border-border space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">Itens por página:</span>
                <Select
                  value={itemsPerPage.toString()}
                  onValueChange={(value) => {
                    setItemsPerPage(Number(value));
                    setCurrentPage(1);
                  }}
                >
                  <SelectTrigger className="w-20">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="5">5</SelectItem>
                    <SelectItem value="10">10</SelectItem>
                    <SelectItem value="20">20</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <span className="text-sm text-muted-foreground">
                Mostrando {startIndex + 1}-{Math.min(startIndex + itemsPerPage, searchResults.length)} de {searchResults.length}
              </span>
            </div>

            <Pagination>
              <PaginationContent>
                <PaginationItem>
                  <PaginationPrevious
                    onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
                    className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                  />
                </PaginationItem>

                {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                  <PaginationItem key={page}>
                    <PaginationLink
                      onClick={() => setCurrentPage(page)}
                      isActive={currentPage === page}
                      className="cursor-pointer"
                    >
                      {page}
                    </PaginationLink>
                  </PaginationItem>
                ))}

                <PaginationItem>
                  <PaginationNext
                    onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
                    className={currentPage === totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
                  />
                </PaginationItem>
              </PaginationContent>
            </Pagination>
          </div>
        )}
      </div>
    </div>
  );
};
