import { useEffect, useState } from 'react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, Loader2, CalendarX2 } from 'lucide-react';
import { absenceService, AbsenceDTO } from '@/modules/rh/services/absenceService';
import { AbsenceForm } from './AbsenceForm';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { toast } from 'sonner';

interface AbsenceListProps {
    agentId: string;
}

export function AbsenceList({ agentId }: AbsenceListProps) {
    const [absences, setAbsences] = useState<AbsenceDTO[]>([]);
    const [loading, setLoading] = useState(true);
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [deletingId, setDeletingId] = useState<string | null>(null);

    const loadAbsences = async () => {
        setLoading(true);
        try {
            // Assuming generic high limit for now as no pagination UI implemented inside tab
            const response = await absenceService.findByAgent(agentId, 0, 100);
            setAbsences(response.content);
        } catch (error) {
            console.error('Failed to load absences', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadAbsences();
    }, [agentId]);

    const handleDelete = async (id: string) => {
        setDeletingId(id);
        try {
            // Wait small delay to show processing state if needed
            await absenceService.delete(id);
            toast.success("Falta removida com sucesso");
            loadAbsences();
        } catch (error: any) {
            toast.error("Erro ao remover falta", { description: error.message });
        } finally {
            setDeletingId(null);
        }
    }

    if (loading) {
        return <div className="flex justify-center p-8"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
    }

    return (
        <div className="space-y-4">
            <div className="flex justify-between items-center">
                <h3 className="text-lg font-medium">Histórico de Faltas</h3>
                <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                    <DialogTrigger asChild>
                        <Button>
                            <Plus className="mr-2 h-4 w-4" />
                            Registrar Falta
                        </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-[500px]">
                        <DialogHeader>
                            <DialogTitle>Registrar Nova Falta</DialogTitle>
                        </DialogHeader>
                        <AbsenceForm
                            agentId={agentId}
                            onSuccess={() => {
                                setIsDialogOpen(false);
                                loadAbsences();
                            }}
                            onCancel={() => setIsDialogOpen(false)}
                        />
                    </DialogContent>
                </Dialog>
            </div>

            <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Início</TableHead>
                            <TableHead>Fim</TableHead>
                            <TableHead>Dias</TableHead>
                            <TableHead>Situação</TableHead>
                            <TableHead>Motivo</TableHead>
                            <TableHead className="w-[100px]"></TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {absences.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={6} className="h-24 text-center text-muted-foreground">
                                    <div className="flex flex-col items-center gap-2">
                                        <CalendarX2 className="h-8 w-8 opacity-20" />
                                        <p>Nenhuma falta registrada</p>
                                    </div>
                                </TableCell>
                            </TableRow>
                        ) : (
                            absences.map((absence) => (
                                <TableRow key={absence.id}>
                                    <TableCell>
                                        {format(new Date(absence.startDate), 'dd/MM/yyyy')}
                                    </TableCell>
                                    <TableCell>
                                        {format(new Date(absence.endDate), 'dd/MM/yyyy')}
                                    </TableCell>
                                    <TableCell>{absence.days}</TableCell>
                                    <TableCell>
                                        <Badge variant={absence.justified ? 'outline' : 'destructive'}>
                                            {absence.justified ? 'Justificada' : 'Injustificada'}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="max-w-[200px] truncate" title={absence.reason}>
                                        {absence.reason || '-'}
                                    </TableCell>
                                    <TableCell>
                                        <AlertDialog>
                                            <AlertDialogTrigger asChild>
                                                <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive">
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>
                                            </AlertDialogTrigger>
                                            <AlertDialogContent>
                                                <AlertDialogHeader>
                                                    <AlertDialogTitle>Excluir Falta?</AlertDialogTitle>
                                                    <AlertDialogDescription>
                                                        Esta ação não pode ser desfeita. Isso removerá o registro de falta e recalculará descontos futuros se ainda não processados.
                                                    </AlertDialogDescription>
                                                </AlertDialogHeader>
                                                <AlertDialogFooter>
                                                    <AlertDialogCancel>Cancelar</AlertDialogCancel>
                                                    <AlertDialogAction onClick={() => handleDelete(absence.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                                                        {deletingId === absence.id ? <Loader2 className="h-4 w-4 animate-spin" /> : "Excluir"}
                                                    </AlertDialogAction>
                                                </AlertDialogFooter>
                                            </AlertDialogContent>
                                        </AlertDialog>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>
        </div>
    );
}
