"use client";

import { useTransition, useState, useEffect } from 'react';
import { format } from 'date-fns';
import { type Employee, type FinancialRecord } from '@/lib/types';
import { handleDeleteFinancialRecord } from '@/lib/actions';
import { useToast } from '@/hooks/use-toast';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from '@/components/ui/button';
import { formatCurrency } from '@/lib/currency-formatter';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Trash2, Loader2, Pencil } from 'lucide-react';
import { Badge } from '../ui/badge';

type Translation = {
    existingRecordsTitle: string;
    existingRecordsDescription: string;
    tableDescription: string;
    tableAmount: string;
    tableRepayment: string;
    tableActions: string;
    deleteRecordTitle: string;
    deleteRecordDescription: string;
    deleteButton: string;
    recordTypeAdvance: string;
    recordTypeRepayment: string;
    recordTypeDeduction: string;
    recordTypeBonus: string;
    edit: string;
    delete: string;
};

type GlobalTranslation = {
    cancel: string;
}

type FinancialRecordsListProps = {
    employee: Employee;
    t: Translation;
    tGlobal: GlobalTranslation;
    onEdit?: (record: FinancialRecord) => void;
    currencySymbol?: string;
}

// New component to handle client-side rendering of dates
function RepaymentCell({ record }: { record: FinancialRecord }) {
    const [isClient, setIsClient] = useState(false);

    useEffect(() => {
        setIsClient(true);
    }, []);

    if (!isClient) {
        return <span className="italic text-muted-foreground">Loading...</span>;
    }

    if (record.installments.length <= 1) {
        return <>One-time on {format(new Date(record.installments[0].date), 'MMM yyyy')}</>;
    }

    const firstInstallment = record.installments[0];
    const lastInstallment = record.installments[record.installments.length - 1];
    
    return <>{`${record.installments.length} installments from ${format(new Date(firstInstallment.date), 'MMM yyyy')} to ${format(new Date(lastInstallment.date), 'MMM yyyy')}`}</>;
}


export default function FinancialRecordsList({ employee, t, tGlobal, onEdit = () => {}, currencySymbol = '$' }: FinancialRecordsListProps) {
    const [isPending, startTransition] = useTransition();
    const { toast } = useToast();

    const onDelete = (recordId: string) => {
        startTransition(async () => {
            const result = await handleDeleteFinancialRecord(employee.id, recordId);
            if (result.success) {
                toast({ title: 'تم الحذف', description: 'تم حذف السجل المالي.' });
            } else {
                toast({ title: 'خطأ', description: result.error || 'تعذر حذف السجل.', variant: 'destructive' });
            }
        });
    };

    const getRecordType = (record: FinancialRecord) => {
        const isAdvanceDisbursement = record.description.startsWith('Manual Advance:') && record.totalAmount < 0;
        const isAdvanceRepayment = record.description === 'Salary Advance Repayment' && record.totalAmount > 0;
        
        if (isAdvanceDisbursement) return <Badge variant="outline" className="text-blue-600 border-blue-600">{t.recordTypeAdvance || 'Advance Disbursed'}</Badge>;
        if (isAdvanceRepayment) return <Badge variant="outline" className="text-orange-600 border-orange-600">{t.recordTypeRepayment || 'Advance Repayment'}</Badge>;
        
        // Fallback for older records or one-time entries
        if (record.totalAmount < 0) return <Badge variant="secondary" className="bg-green-100 text-green-800">{t.recordTypeBonus || 'One-time Bonus'}</Badge>;
        return <Badge variant="destructive" className="bg-red-100 text-red-800">{t.recordTypeDeduction || 'One-time Deduction'}</Badge>;
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle>{t.existingRecordsTitle}</CardTitle>
                <CardDescription>{t.existingRecordsDescription}</CardDescription>
            </CardHeader>
            <CardContent>
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Type</TableHead>
                            <TableHead>{t.tableDescription}</TableHead>
                            <TableHead className="text-right">{t.tableAmount}</TableHead>
                            <TableHead>{t.tableRepayment}</TableHead>
                            <TableHead className="text-right">{t.tableActions}</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {employee.financialRecords.length === 0 && (
                            <TableRow>
                                <TableCell colSpan={5} className="text-center h-24 text-muted-foreground">No records found.</TableCell>
                            </TableRow>
                        )}
                        {employee.financialRecords.map(record => (
                            <TableRow key={record.id}>
                                <TableCell>{getRecordType(record)}</TableCell>
                                <TableCell>{record.description}</TableCell>
                                <TableCell className={`text-right font-medium ${record.totalAmount > 0 ? 'text-red-600' : 'text-green-600'}`}>
                                    {formatCurrency(Math.abs(record.totalAmount), currencySymbol)}
                                </TableCell>
                                <TableCell><RepaymentCell record={record} /></TableCell>
                                <TableCell className="text-right">
                                    <AlertDialog>
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button aria-haspopup="true" size="icon" variant="ghost" disabled={isPending}>
                                                    {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <MoreHorizontal className="h-4 w-4" />}
                                                    <span className="sr-only">Toggle menu</span>
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuLabel>{t.tableActions}</DropdownMenuLabel>
                                                {record.description === 'Salary Advance Repayment' && (
                                                    <DropdownMenuItem onSelect={() => onEdit(record)}>
                                                        <Pencil className="mr-2 h-4 w-4" />
                                                        {t.edit}
                                                    </DropdownMenuItem>
                                                )}
                                                <DropdownMenuSeparator />
                                                <AlertDialogTrigger asChild>
                                                    <DropdownMenuItem className="text-red-600" onSelect={(e) => e.preventDefault()}>
                                                        <Trash2 className="mr-2 h-4 w-4" />
                                                        {t.delete}
                                                    </DropdownMenuItem>
                                                </AlertDialogTrigger>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                        <AlertDialogContent>
                                            <AlertDialogHeader>
                                                <AlertDialogTitle>{t.deleteRecordTitle}</AlertDialogTitle>
                                                <AlertDialogDescription>
                                                   {(t.deleteRecordDescription || '').replace('{description}', record.description)}
                                                </AlertDialogDescription>
                                            </AlertDialogHeader>
                                            <AlertDialogFooter>
                                                <AlertDialogCancel>{tGlobal.cancel}</AlertDialogCancel>
                                                <AlertDialogAction onClick={() => onDelete(record.id)} className="bg-destructive hover:bg-destructive/90">
                                                    {isPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : (t.deleteButton || 'Delete')}
                                                </AlertDialogAction>
                                            </AlertDialogFooter>
                                        </AlertDialogContent>
                                    </AlertDialog>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </CardContent>
        </Card>
    );
}
