import { useState, useEffect } from "react";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow
} from "@/components/ui/table";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { PayrollRunDTO, PayrollPeriodDTO, PayrollItemDTO } from "@/types/rh";
import { MinistryDTO, OrgUnitDTO } from "@/types/org";
import { rhService } from "@/services/rhService";
import { orgService } from "@/services/orgService";
import { Plus, Play, CheckCircle, AlertCircle, RefreshCw, Eye, User, Landmark, Wallet, Download, FileText, FileSpreadsheet, Building2, Trash2, Stethoscope } from "lucide-react";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger
} from "@/components/ui/dialog";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";

export function PayrollRunsPage() {
    const [runs, setRuns] = useState<PayrollRunDTO[]>([]);
    const [periods, setPeriods] = useState<PayrollPeriodDTO[]>([]);
    const [loading, setLoading] = useState(true);
    const [openModal, setOpenModal] = useState(false);
    const [selectedRun, setSelectedRun] = useState<PayrollRunDTO | null>(null);
    const [detailsOpen, setDetailsOpen] = useState(false);
    const [detailsLoading, setDetailsLoading] = useState(false);

    // Form states
    const [selectedPeriod, setSelectedPeriod] = useState("");
    const [runType, setRunType] = useState("NORMAL");
    const [selectedMinistry, setSelectedMinistry] = useState("");
    const [selectedOrgUnit, setSelectedOrgUnit] = useState("");

    // Ministries and Org Units
    const [ministries, setMinistries] = useState<MinistryDTO[]>([]);
    const [orgUnits, setOrgUnits] = useState<OrgUnitDTO[]>([]);

    // Diagnosis
    const [diagnosisOpen, setDiagnosisOpen] = useState(false);
    const [diagnosisData, setDiagnosisData] = useState<any>(null);
    const [diagnosisLoading, setDiagnosisLoading] = useState(false);

    useEffect(() => {
        loadData();
    }, []);

    const loadData = async () => {
        setLoading(true);
        try {
            const [runsData, periodsData, ministriesData] = await Promise.all([
                rhService.getPayrollRuns(),
                rhService.getPayrollPeriods(),
                orgService.getMinistries({ size: 100 })
            ]);
            setRuns(runsData);
            setPeriods(periodsData);
            setMinistries(ministriesData.content || []);
        } catch (error) {
            toast.error("Erro ao carregar dados de folha");
        } finally {
            setLoading(false);
        }
    };

    // Carregar unidades orgânicas quando ministério é selecionado
    useEffect(() => {
        if (selectedMinistry) {
            orgService.getOrgUnitTree(selectedMinistry)
                .then(units => setOrgUnits(units))
                .catch(() => setOrgUnits([]));
        } else {
            setOrgUnits([]);
            setSelectedOrgUnit("");
        }
    }, [selectedMinistry]);

    const handleCreateRun = async () => {
        if (!selectedPeriod) {
            toast.error("Selecione um período");
            return;
        }
        if (!selectedMinistry) {
            toast.error("Selecione um ministério");
            return;
        }

        try {
            await rhService.createPayrollRun({
                periodId: selectedPeriod,
                ministryId: selectedMinistry,
                orgUnitId: selectedOrgUnit || undefined,
                runType: runType
            });
            toast.success("Execução de folha criada!");
            setOpenModal(false);
            setSelectedMinistry("");
            setSelectedOrgUnit("");
            loadData();
        } catch (error: any) {
            const msg = error?.response?.data?.message || "Erro ao criar execução";
            toast.error(msg);
        }
    };

    const handleGenerate = async (id: string) => {
        try {
            toast.info("Gerando itens de folha...");
            await rhService.generatePayrollItems(id);
            toast.success("Itens gerados com sucesso!");
            loadData();
        } catch (error: any) {
            const msg = error?.response?.data?.message || "Erro ao gerar itens";
            toast.error(msg);
        }
    };

    const handleProcess = async (id: string) => {
        try {
            toast.info("Processando folha e integrando com orçamento...");
            await rhService.processPayrollRun(id);
            toast.success("Folha processada e integrada!");
            loadData();
        } catch (error: any) {
            const msg = error?.response?.data?.message || "Erro ao processar folha";
            toast.error(msg);
        }
    };

    const handleClose = async (id: string) => {
        if (!window.confirm("Tem certeza que deseja encerrar definitivamente esta folha? Isto disparará a liquidação orçamentária final.")) {
            return;
        }

        try {
            toast.info("Encerrando folha e liquidando orçamento...");
            await rhService.closePayrollRun(id);
            toast.success("Folha encerrada e liquidada com sucesso!");
            loadData();
        } catch (error: any) {
            const msg = error?.response?.data?.message || "Erro ao encerrar folha";
            toast.error(msg);
        }
    };

    const handleDelete = async (id: string) => {
        if (!window.confirm("Tem certeza que deseja excluir esta execução de folha?")) {
            return;
        }

        try {
            await rhService.deletePayrollRun(id);
            toast.success("Execução de folha excluída!");
            loadData();
        } catch (error: any) {
            const msg = error?.response?.data?.message || "Erro ao excluir execução";
            toast.error(msg);
        }
    };

    const handleExport = async (id: string, format: 'pdf' | 'xlsx') => {
        try {
            await rhService.exportPayrollRun(id, format);
            toast.success(`Relatório ${format.toUpperCase()} gerado com sucesso`);
        } catch (error: any) {
            const msg = error?.response?.data?.message || "Erro ao gerar relatório";
            toast.error(msg);
        }
    };

    const handleViewDetails = async (run: PayrollRunDTO) => {
        setSelectedRun(run);
        setDetailsOpen(true);
        setDetailsLoading(true);
        try {
            const fullRun = await rhService.getPayrollRunById(run.id);
            setSelectedRun(fullRun);
        } catch (error) {
            toast.error("Erro ao carregar detalhes da execução");
        } finally {
            setDetailsLoading(false);
        }
    };

    const handleDiagnose = async (id: string) => {
        setDiagnosisLoading(true);
        setDiagnosisOpen(true);
        try {
            const data = await rhService.diagnosePayrollRun(id);
            setDiagnosisData(data);
        } catch (error) {
            toast.error("Erro ao executar diagnóstico");
            setDiagnosisOpen(false);
        } finally {
            setDiagnosisLoading(false);
        }
    };

    // Agrupar itens por agente
    const groupedItemsByAgent = selectedRun?.items?.reduce((acc, item) => {
        if (!acc[item.agent]) {
            acc[item.agent] = {
                agentId: item.agent,
                agentName: item.agentName,
                earnings: [],
                deductions: [],
                totalEarnings: 0,
                totalDeductions: 0
            };
        }
        if (item.lineType === 'EARNING') {
            acc[item.agent].earnings.push(item);
            acc[item.agent].totalEarnings += item.totalAmount;
        } else {
            acc[item.agent].deductions.push(item);
            acc[item.agent].totalDeductions += item.totalAmount;
        }
        return acc;
    }, {} as Record<string, { agentId: string, agentName?: string, earnings: PayrollItemDTO[], deductions: PayrollItemDTO[], totalEarnings: number, totalDeductions: number }>);

    const getStatusBadge = (status: string) => {
        switch (status) {
            case "PENDING": return <Badge variant="outline">Pendente</Badge>;
            case "GENERATED": return <Badge variant="secondary" className="bg-blue-100 text-blue-800">Gerado</Badge>;
            case "PROCESSING": return <Badge variant="secondary" className="bg-yellow-100 text-yellow-800 animate-pulse">Processando</Badge>;
            case "COMPLETED": return <Badge variant="default" className="bg-blue-100 text-blue-800 border-blue-200">Processado</Badge>;
            case "CLOSED": return <Badge variant="default" className="bg-green-100 text-green-800 border-green-200">Encerrado</Badge>;
            case "FAILED": return <Badge variant="destructive">Falhou</Badge>;
            default: return <Badge variant="outline">{status}</Badge>;
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">Execuções de Folha</h2>
                    <p className="text-muted-foreground">Gerencie o processamento mensal de salários</p>
                </div>

                <Dialog open={openModal} onOpenChange={setOpenModal}>
                    <DialogTrigger asChild>
                        <Button> <Plus className="mr-2 h-4 w-4" /> Nova Execução</Button>
                    </DialogTrigger>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Criar Nova Execução de Folha</DialogTitle>
                            <DialogDescription>
                                Selecione o período e o tipo de execução para iniciar.
                            </DialogDescription>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                            <div className="grid gap-2">
                                <Label htmlFor="period">Período Fiscal</Label>
                                <Select onValueChange={setSelectedPeriod} value={selectedPeriod}>
                                    <SelectTrigger id="period">
                                        <SelectValue placeholder="Selecione o mês/ano" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {periods.filter(p => p.status === 'OPEN').map(p => (
                                            <SelectItem key={p.id} value={p.id}>
                                                {p.month}/{p.fiscalYear}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="ministry">Ministério *</Label>
                                <Select onValueChange={setSelectedMinistry} value={selectedMinistry}>
                                    <SelectTrigger id="ministry">
                                        <SelectValue placeholder="Selecione o ministério" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {ministries.filter(m => m.id).map(m => (
                                            <SelectItem key={m.id} value={m.id}>
                                                {m.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="orgUnit">Unidade Orgânica</Label>
                                <Select
                                    onValueChange={setSelectedOrgUnit}
                                    value={selectedOrgUnit}
                                    disabled={!selectedMinistry}
                                >
                                    <SelectTrigger id="orgUnit">
                                        <SelectValue placeholder={selectedMinistry ? "Todas as unidades" : "Selecione primeiro o ministério"} />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {orgUnits.filter(u => u.id).map(u => (
                                            <SelectItem key={u.id} value={u.id}>
                                                {u.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="type">Tipo de Execução</Label>
                                <Select onValueChange={setRunType} value={runType}>
                                    <SelectTrigger id="type">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="NORMAL">Normal (Mensal)</SelectItem>
                                        <SelectItem value="SUPPLEMENTARY">Suplementar</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setOpenModal(false)}>Cancelar</Button>
                            <Button onClick={handleCreateRun}>Criar Execução</Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle>Execuções Recentes</CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Período</TableHead>
                                <TableHead>Ministério</TableHead>
                                <TableHead>Unidade Orgânica</TableHead>
                                <TableHead>Tipo</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead>Criado em</TableHead>
                                <TableHead className="text-right">Ações</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {loading ? (
                                <TableRow>
                                    <TableCell colSpan={7} className="text-center py-10">Carregando...</TableCell>
                                </TableRow>
                            ) : runs.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={7} className="text-center py-10 text-muted-foreground">
                                        Nenhuma execução encontrada.
                                    </TableCell>
                                </TableRow>
                            ) : runs.map((run) => {
                                const period = periods.find(p => p.id === run.periodId);
                                return (
                                    <TableRow key={run.id}>
                                        <TableCell className="font-medium">
                                            {period ? `${period.month}/${period.fiscalYear}` : "N/A"}
                                        </TableCell>
                                        <TableCell>{run.ministryName || "Geral"}</TableCell>
                                        <TableCell>{run.orgUnitName || "Geral"}</TableCell>
                                        <TableCell>{run.runType}</TableCell>
                                        <TableCell>{getStatusBadge(run.status)}</TableCell>
                                        <TableCell>{new Date(run.createdAt).toLocaleString()}</TableCell>
                                        <TableCell className="text-right space-x-2">
                                            {run.status === "PENDING" && (
                                                <Button size="sm" variant="outline" onClick={() => handleGenerate(run.id)}>
                                                    <Play className="mr-2 h-4 w-4" /> Gerar Itens
                                                </Button>
                                            )}
                                            {run.status === "GENERATED" && (
                                                <Button size="sm" variant="default" onClick={() => handleProcess(run.id)}>
                                                    <Play className="mr-2 h-4 w-4" /> Processar
                                                </Button>
                                            )}
                                            {run.status === "COMPLETED" && (
                                                <Button size="sm" variant="default" className="bg-green-600 hover:bg-green-700" onClick={() => handleClose(run.id)}>
                                                    <CheckCircle className="mr-2 h-4 w-4" /> Fechar Definitivamente
                                                </Button>
                                            )}
                                            {run.status === "FAILED" && (
                                                <Button size="sm" variant="destructive" onClick={() => handleGenerate(run.id)}>
                                                    <RefreshCw className="mr-2 h-4 w-4" /> Tentar Novamente
                                                </Button>
                                            )}
                                            <Button size="sm" variant="ghost" onClick={() => handleViewDetails(run)}>
                                                <Eye className="mr-2 h-4 w-4" /> Detalhes
                                            </Button>
                                            <Button size="sm" variant="ghost" onClick={() => handleDiagnose(run.id)} title="Diagnóstico">
                                                <Stethoscope className="h-4 w-4" />
                                            </Button>

                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button size="sm" variant="outline">
                                                        <Download className="h-4 w-4" />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem onClick={() => handleExport(run.id, 'pdf')}>
                                                        <FileText className="mr-2 h-4 w-4" /> Exportar PDF
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem onClick={() => handleExport(run.id, 'xlsx')}>
                                                        <FileSpreadsheet className="mr-2 h-4 w-4" /> Exportar Excel
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>

                                            {(run.status === "PENDING" || run.status === "GENERATED") && (
                                                <Button size="sm" variant="destructive" onClick={() => handleDelete(run.id)}>
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>
                                            )}
                                        </TableCell>
                                    </TableRow>
                                );
                            })}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>

            {/* Modal de Detalhes da Execução */}
            <Dialog open={detailsOpen} onOpenChange={setDetailsOpen}>
                <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Detalhes da Execução de Folha</DialogTitle>
                        <DialogDescription>
                            Visualização analítica dos vencimentos e impostos processados.
                        </DialogDescription>
                    </DialogHeader>

                    {detailsLoading ? (
                        <div className="py-20 text-center">Carregando detalhes...</div>
                    ) : (
                        <div className="space-y-6">
                            {groupedItemsByAgent && Object.values(groupedItemsByAgent).length > 0 ? (
                                Object.values(groupedItemsByAgent).map((group) => (
                                    <Card key={group.agentId} className="border-l-4 border-l-primary">
                                        <CardHeader className="pb-2">
                                            <div className="flex justify-between items-center">
                                                <div className="flex items-center space-x-2">
                                                    <User className="h-5 w-5 text-muted-foreground" />
                                                    <CardTitle className="text-lg">
                                                        {group.agentName ? group.agentName : `Agente ID: ${group.agentId}`}
                                                    </CardTitle>
                                                </div>
                                                <div className="text-right">
                                                    <p className="text-sm text-muted-foreground">Líquido a Receber</p>
                                                    <p className="text-xl font-bold text-primary">
                                                        {(group.totalEarnings - group.totalDeductions).toLocaleString('pt-PT', { style: 'currency', currency: 'XOF' })}
                                                    </p>
                                                </div>
                                            </div>
                                        </CardHeader>
                                        <CardContent>
                                            <div className="grid grid-cols-2 gap-4">
                                                <div>
                                                    <h4 className="text-sm font-semibold mb-2 flex items-center">
                                                        <Wallet className="mr-2 h-4 w-4 text-green-600" /> Rendimentos
                                                    </h4>
                                                    <ul className="space-y-1">
                                                        {group.earnings.map(item => (
                                                            <li key={item.id} className="text-sm flex justify-between">
                                                                <span>{item.description}</span>
                                                                <span className="font-medium">{item.totalAmount.toLocaleString()}</span>
                                                            </li>
                                                        ))}
                                                    </ul>
                                                </div>
                                                <div className="border-l pl-4">
                                                    <h4 className="text-sm font-semibold mb-2 flex items-center">
                                                        <Landmark className="mr-2 h-4 w-4 text-red-600" /> Impostos e Descontos
                                                    </h4>
                                                    <ul className="space-y-1">
                                                        {group.deductions.map(item => (
                                                            <li key={item.id} className="text-sm flex justify-between">
                                                                <span>{item.description}</span>
                                                                <span className="font-medium text-red-600">-{item.totalAmount.toLocaleString()}</span>
                                                            </li>
                                                        ))}
                                                    </ul>
                                                </div>
                                            </div>
                                        </CardContent>
                                    </Card>
                                ))
                            ) : (
                                <div className="text-center py-10 text-muted-foreground italic">
                                    Nenhum item gerado para esta execução.
                                </div>
                            )}
                        </div>
                    )}
                    <DialogFooter>
                        <Button onClick={() => setDetailsOpen(false)}>Fechar</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Modal de Diagnóstico */}
            <Dialog open={diagnosisOpen} onOpenChange={setDiagnosisOpen}>
                <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Diagnóstico de Geração de Folha</DialogTitle>
                        <DialogDescription>
                            Verifica todos os requisitos para geração de itens.
                        </DialogDescription>
                    </DialogHeader>
                    {diagnosisLoading ? (
                        <div className="flex items-center justify-center py-10">
                            <RefreshCw className="h-8 w-8 animate-spin" />
                        </div>
                    ) : diagnosisData ? (
                        <div className="space-y-6">
                            {/* Resumo Geral */}
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                <Card>
                                    <CardContent className="pt-4">
                                        <div className="text-2xl font-bold">{diagnosisData.totalAgentsInDatabase || 0}</div>
                                        <div className="text-sm text-muted-foreground">Total Agentes no BD</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardContent className="pt-4">
                                        <div className="text-2xl font-bold">{diagnosisData.activeAgentsCount || 0}</div>
                                        <div className="text-sm text-muted-foreground">Status ACTIVE</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardContent className="pt-4">
                                        <div className="text-2xl font-bold">{diagnosisData.eligibleAgentsCount || 0}</div>
                                        <div className="text-sm text-muted-foreground">Aptos para Folha</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardContent className="pt-4">
                                        <div className="text-2xl font-bold">{diagnosisData.salaryGridsCount || 0}</div>
                                        <div className="text-sm text-muted-foreground">Tabelas Salariais</div>
                                    </CardContent>
                                </Card>
                            </div>

                            {/* Status por Tipo */}
                            {diagnosisData.agentsByStatus && (
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="text-lg">Agentes por Status</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="flex flex-wrap gap-2">
                                            {Object.entries(diagnosisData.agentsByStatus).map(([status, count]) => (
                                                <Badge key={status} variant={status === 'ACTIVE' ? 'default' : 'secondary'}>
                                                    {status}: {String(count)}
                                                </Badge>
                                            ))}
                                        </div>
                                    </CardContent>
                                </Card>
                            )}

                            {/* Tipos de Provento Configurados */}
                            {diagnosisData.earningTypesConfigured && (
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="text-lg">Tipos de Provento</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="flex flex-wrap gap-2">
                                            {Object.entries(diagnosisData.earningTypesConfigured).map(([type, configured]) => (
                                                <Badge key={type} variant={configured ? 'default' : 'destructive'}>
                                                    {type}: {configured ? '✓' : '✗'}
                                                </Badge>
                                            ))}
                                        </div>
                                    </CardContent>
                                </Card>
                            )}

                            {/* Diagnóstico por Agente */}
                            {diagnosisData.agentDiagnosis && diagnosisData.agentDiagnosis.length > 0 && (
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="text-lg">Diagnóstico por Agente (Status ACTIVE)</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <Table>
                                            <TableHeader>
                                                <TableRow>
                                                    <TableHead>Matrícula</TableHead>
                                                    <TableHead>Nome</TableHead>
                                                    <TableHead>Apto</TableHead>
                                                    <TableHead>Problemas</TableHead>
                                                </TableRow>
                                            </TableHeader>
                                            <TableBody>
                                                {diagnosisData.agentDiagnosis.map((agent: any, idx: number) => (
                                                    <TableRow key={idx}>
                                                        <TableCell>{agent.matricula}</TableCell>
                                                        <TableCell>{agent.fullName}</TableCell>
                                                        <TableCell>
                                                            {agent.canGenerateItems ? (
                                                                <CheckCircle className="h-5 w-5 text-green-500" />
                                                            ) : (
                                                                <AlertCircle className="h-5 w-5 text-red-500" />
                                                            )}
                                                        </TableCell>
                                                        <TableCell>
                                                            {agent.issues?.length > 0 ? (
                                                                <ul className="list-disc list-inside text-sm text-red-600">
                                                                    {agent.issues.map((issue: string, i: number) => (
                                                                        <li key={i}>{issue}</li>
                                                                    ))}
                                                                </ul>
                                                            ) : (
                                                                <span className="text-green-600 text-sm">Sem problemas</span>
                                                            )}
                                                        </TableCell>
                                                    </TableRow>
                                                ))}
                                            </TableBody>
                                        </Table>
                                    </CardContent>
                                </Card>
                            )}

                            {diagnosisData.activeAgentsCount === 0 && (
                                <div className="bg-yellow-50 border border-yellow-200 rounded-md p-4">
                                    <p className="text-yellow-800 font-medium">⚠️ Nenhum agente com status ACTIVE encontrado!</p>
                                    <p className="text-yellow-700 text-sm mt-1">
                                        Os agentes precisam ter status "ACTIVE" para serem incluídos na folha.
                                        Verifique se os agentes cadastrados estão com o status correto.
                                    </p>
                                </div>
                            )}
                        </div>
                    ) : null}
                    <DialogFooter>
                        <Button onClick={() => setDiagnosisOpen(false)}>Fechar</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}
