import { DownloadIcon } from '@phosphor-icons/react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import type { SearchParams } from './app/models';
import { diarioApi } from './app/services';
import { DiariosList } from './views/components/diario-list';
import { Footer } from './views/components/footer';
import { Header } from './views/components/header';
import { InfoSection } from './views/components/info-section';
import { SearchForm } from './views/components/search-form';
import { Button } from './views/components/ui/button';

export function App() {
  const [searchParams, setSearchParams] = useState<SearchParams>({
    entidade: '',
    grupo: '',
    subgrupo: '',
    ano: '',
    periodoDe: '',
    periodoAte: '',
    certificado: '',
    palavraChave: '',
  });

  const queryClient = useQueryClient();

  const { data: ultimosDiarios, isLoading: isLoadingUltimos } = useQuery({
    queryKey: ['ultimos-diarios'],
    queryFn: () => diarioApi.buscarUltimosDiarios(),
  });

  const {
    data: diariosFiltrados,
    isLoading: isLoadingBusca,
    refetch: buscarDiarios,
  } = useQuery({
    queryKey: ['diarios-filtrados', searchParams],
    queryFn: () => diarioApi.buscarDiarios(searchParams),
    enabled: false,
  });

  function handleParamChange(field: keyof SearchParams, value: string) {
    setSearchParams((prev) => ({ ...prev, [field]: value }));
  }

  function handleSearch() {
    buscarDiarios();
  }

  function handleClear() {
    setSearchParams({
      entidade: '',
      grupo: '',
      subgrupo: '',
      ano: '',
      periodoDe: '',
      periodoAte: '',
      certificado: '',
      palavraChave: '',
    });
    queryClient.invalidateQueries({ queryKey: ['ultimos-diarios'] });
  }

  const handleDownload = async (id: number) => {
    try {
      const diario = await diarioApi.buscarDiarioPorId(id);

      alert(`Download do diário: ${diario.titulo}`);
    } catch (error) {
      console.error('Erro ao baixar diário:', error);
    }
  };

  const handleView = (id: number) => {
    console.log('Visualizar diário:', id);
  };

  const handleExport = async () => {
    try {
      alert('Exportando resultados...');
    } catch (error) {
      console.error('Erro ao exportar:', error);
    }
  };

  return (
    <div className="min-h-screen bg-linear-to-b from-slate-50 to-gray-100 dark:from-gray-900 dark:to-slate-950">
      <Header />

      <div className="container mx-auto px-4 py-8 space-y-8">
        <SearchForm
          searchParams={searchParams}
          onSearch={handleSearch}
          onClear={handleClear}
          onParamChange={handleParamChange}
          isLoading={isLoadingBusca}
        />

        {diariosFiltrados?.data && diariosFiltrados.data.length > 0 && (
          <div className="flex justify-end">
            <Button variant="outline" onClick={handleExport} className="gap-2">
              <DownloadIcon size={18} />
              Exportar Resultados
            </Button>
          </div>
        )}

        {diariosFiltrados?.data ? (
          <DiariosList
            diarios={diariosFiltrados.data}
            title="Resultados da Busca"
            subtitle={`${diariosFiltrados.total} diários encontrados com os filtros aplicados`}
            loading={isLoadingBusca}
            onDownload={handleDownload}
            onView={handleView}
          />
        ) : (
          <DiariosList
            diarios={ultimosDiarios || []}
            loading={isLoadingUltimos}
            onDownload={handleDownload}
            onView={handleView}
          />
        )}

        <InfoSection />
      </div>

      <Footer />
    </div>
  );
}
