
'use client';

import { useTransition, useState, useEffect, useMemo } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { addMonths, format, getYear, getMonth } from "date-fns";

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { type Employee, type FinancialRecord, type LeaveRequest } from "@/lib/types";
import { handleUpdateFinancialRecord } from "@/lib/actions";
import { Loader2, PlusCircle, Trash2 } from "lucide-react";
import { Separator } from "../ui/separator";
import { formatCurrency } from "@/lib/currency-formatter";


type Translation = {
    title: string;
    description: string;
    advanceTitle: string;
    advanceDescription: string;
    oneTimeTitle: string;
    oneTimeDescription: string;
    descriptionLabel: string;
    totalAmountLabel: string;
    repaymentStartLabel: string;
    month: string;
    year: string;
    saveAdvanceButton: string;
    amountLabel: string;
    recordTypeLabel: string;
    deduction: string;
    bonus: string;
    addRecordButton: string;
    selectAdvanceTitle: string;
    selectAdvanceDescription: string;
    approvedRequestLabel: string;
    selectRequestPlaceholder: string;
    manualAdvanceTitle: string;
    installmentsScheduleTitle: string;
    addInstallmentButton: string;
    installmentAmount: string;
    installmentDate: string;
    scheduledTotal: string;
    remainingAmount: string;
    amountMismatchError: string;
}

type GlobalTranslation = {
    cancel: string;
}

type FinancialsFormProps = {
    employee: Employee;
    t: Translation;
    tGlobal: GlobalTranslation;
    unscheduledApprovedRequests: UnscheduledRequest[];
    currencySymbol?: string;
}

const advanceScheduleSchema = z.object({
  description: z.string().min(2, "Description is required.").default("Salary Advance"),
  totalAmount: z.coerce.number().min(1, "Total amount must be greater than zero."),
  installments: z.array(z.object({
      month: z.string(),
      year: z.string(),
      amount: z.coerce.number().min(0.01, "Amount must be positive.")
  })).min(1, "At least one installment is required."),
  requestId: z.string().nullable(),
}).refine(data => {
    const totalInstallments = data.installments.reduce((sum, inst) => sum + inst.amount, 0);
    return Math.abs(data.totalAmount - totalInstallments) < 0.01;
}, {
    message: "The sum of installments must equal the total advance amount.",
    path: ["installments"],
});

const oneTimeRecordSchema = z.object({
  description: z.string().min(2, "Description is required."),
  amount: z.coerce.number().min(0.01, "Amount must be positive."),
  month: z.string(),
  year: z.string(),
  recordType: z.enum(['deduction', 'bonus']),
});


type UnscheduledRequest = Omit<LeaveRequest, 'employeeId' | 'employeeName' | 'toEmployeeName'>;

export default function FinancialsForm({ employee, t, tGlobal, unscheduledApprovedRequests, currencySymbol = '$' }: FinancialsFormProps) {
    const [isPending, startTransition] = useTransition();
    const { toast } = useToast();
    const [selectedRequestId, setSelectedRequestId] = useState<string | null>(null);
    
    const today = new Date();
    const years = Array.from({ length: 5 }, (_, i) => String(getYear(today) + i));
    const months = Array.from({ length: 12 }, (_, i) => ({ value: String(i), label: format(new Date(today.getFullYear(), i), 'MMMM') }));

    const advanceForm = useForm<z.infer<typeof advanceScheduleSchema>>({
        resolver: zodResolver(advanceScheduleSchema),
        defaultValues: {
            description: "Salary Advance",
            totalAmount: 0,
            installments: [],
            requestId: null,
        },
    });

    const { fields, append, remove } = useFieldArray({
        control: advanceForm.control,
        name: "installments",
    });

    const watchInstallments = advanceForm.watch("installments");
    const watchTotalAmount = advanceForm.watch("totalAmount");

    const scheduledTotal = useMemo(() => {
        return (watchInstallments || []).reduce((sum, inst) => sum + (Number(inst.amount) || 0), 0);
    }, [watchInstallments]);

    const remainingAmount = watchTotalAmount - scheduledTotal;

    const oneTimeForm = useForm<z.infer<typeof oneTimeRecordSchema>>({
        resolver: zodResolver(oneTimeRecordSchema),
        defaultValues: {
            description: "",
            amount: 0,
            month: String(getMonth(today)),
            year: String(getYear(today)),
            recordType: "deduction",
        },
    });

    const handleRequestSelect = (requestId: string) => {
        const selectedRequest = unscheduledApprovedRequests.find(r => r.id === requestId);
        if (selectedRequest) {
            advanceForm.setValue('totalAmount', selectedRequest.amount || 0);
            advanceForm.setValue('description', `From request: ${selectedRequest.reason || 'Salary Advance'}`);
            advanceForm.setValue('installments', []); // Reset installments
            setSelectedRequestId(selectedRequest.id);
        } else {
             advanceForm.setValue('totalAmount', 0);
            advanceForm.setValue('description', `Salary Advance`);
            setSelectedRequestId(null);
        }
    }

    async function onAdvanceSubmit(values: z.infer<typeof advanceScheduleSchema>) {
        startTransition(async () => {
            const result = await handleUpdateFinancialRecord(employee.id, 'advance', {...values});
            if (result?.success) {
                toast({ title: 'تمت الجدولة', description: 'تمت جدولة سلفة الراتب بنجاح.' });
                advanceForm.reset({
                    description: "Salary Advance",
                    totalAmount: 0,
                    installments: [],
                    requestId: null,
                });
                setSelectedRequestId(null);
            } else {
                toast({ title: 'خطأ', description: result?.error || 'تعذر إنشاء الجدولة.', variant: 'destructive' });
            }
        });
    }

    async function onOneTimeSubmit(values: z.infer<typeof oneTimeRecordSchema>) {
        startTransition(async () => {
            const date = new Date(parseInt(values.year), parseInt(values.month));
            const result = await handleUpdateFinancialRecord(employee.id, 'oneTime', {...values, date});
            
            if (result?.success) {
                toast({ title: 'تمت الإضافة', description: 'تمت إضافة السجل المالي بنجاح.' });
                oneTimeForm.reset();
            } else {
                toast({ title: 'خطأ', description: result?.error || 'تعذر إضافة السجل.', variant: 'destructive' });
            }
        });
    }
    
    return (
       <div className="space-y-8">
            <Card>
                <CardHeader>
                    <CardTitle>{t.selectAdvanceTitle}</CardTitle>
                    <CardDescription>
                        {t.selectAdvanceDescription}
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <Form {...advanceForm}>
                        <form onSubmit={advanceForm.handleSubmit(onAdvanceSubmit)} className="space-y-6">
                             {unscheduledApprovedRequests.length > 0 && (
                                <>
                                <FormItem>
                                    <FormLabel>{t.approvedRequestLabel}</FormLabel>
                                    <Select onValueChange={handleRequestSelect} value={selectedRequestId || ""}>
                                        <FormControl><SelectTrigger><SelectValue placeholder={t.selectRequestPlaceholder} /></SelectTrigger></FormControl>
                                        <SelectContent>
                                            {unscheduledApprovedRequests.map(req => (
                                                <SelectItem key={req.id} value={req.id}>
                                                    {format(new Date(req.from!), 'MMM d, yyyy')} - {formatCurrency(req.amount || 0, currencySymbol)} - {req.reason}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </FormItem>
                                <div className="flex items-center gap-4">
                                    <Separator className="flex-1" />
                                    <span className="text-xs text-muted-foreground">{t.manualAdvanceTitle}</span>
                                    <Separator className="flex-1" />
                                </div>
                                </>
                             )}

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
                                <div className="sm:col-span-2">
                                    <FormField control={advanceForm.control} name="description" render={({ field }) => (
                                        <FormItem><FormLabel>{t.descriptionLabel}</FormLabel><FormControl><Input {...field} readOnly={!!selectedRequestId} /></FormControl><FormMessage /></FormItem>
                                    )} />
                                </div>
                                
                                <FormField control={advanceForm.control} name="totalAmount" render={({ field }) => (
                                    <FormItem><FormLabel>{t.totalAmountLabel}</FormLabel><FormControl><Input type="number" step="0.01" {...field} readOnly={!!selectedRequestId} /></FormControl><FormMessage /></FormItem>
                                )} />
                            </div>

                             <Separator />
                            
                             <div>
                                <h4 className="text-sm font-medium mb-4">{t.installmentsScheduleTitle}</h4>
                                <div className="space-y-3">
                                    {fields.map((field, index) => (
                                        <div key={field.id} className="grid grid-cols-12 gap-2 items-start">
                                            <FormField control={advanceForm.control} name={`installments.${index}.amount`} render={({ field }) => (
                                                <FormItem className="col-span-5"><FormLabel className="sr-only">Amount</FormLabel><FormControl><Input type="number" step="0.01" placeholder={t.installmentAmount} {...field} /></FormControl><FormMessage /></FormItem>
                                            )} />
                                            <FormField control={advanceForm.control} name={`installments.${index}.month`} render={({ field }) => (
                                                <FormItem className="col-span-3"><FormLabel className="sr-only">Month</FormLabel>
                                                    <Select onValueChange={field.onChange} defaultValue={field.value}><FormControl><SelectTrigger><SelectValue placeholder={t.month} /></SelectTrigger></FormControl>
                                                        <SelectContent>{months.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
                                                    </Select>
                                                </FormItem>
                                            )} />
                                             <FormField control={advanceForm.control} name={`installments.${index}.year`} render={({ field }) => (
                                                <FormItem className="col-span-3"><FormLabel className="sr-only">Year</FormLabel>
                                                    <Select onValueChange={field.onChange} defaultValue={field.value}><FormControl><SelectTrigger><SelectValue placeholder={t.year} /></SelectTrigger></FormControl>
                                                        <SelectContent>{years.map(y => <SelectItem key={y} value={y}>{y}</SelectItem>)}</SelectContent>
                                                    </Select>
                                                </FormItem>
                                            )} />
                                            <Button type="button" variant="ghost" size="icon" className="col-span-1 text-muted-foreground" onClick={() => remove(index)}><Trash2 className="h-4 w-4" /></Button>
                                        </div>
                                    ))}
                                    <Button type="button" variant="outline" size="sm" onClick={() => append({ month: String(getMonth(today)), year: String(getYear(today)), amount: 0 })} className="mt-2">
                                        <PlusCircle className="me-2 h-4 w-4" />{t.addInstallmentButton}
                                    </Button>
                                </div>
                            </div>
                            
                            <div className="mt-4 p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
                                <div className="flex justify-between"><span>{t.totalAmountLabel}</span><span className="font-medium">{formatCurrency(watchTotalAmount, currencySymbol)}</span></div>
                                <div className="flex justify-between"><span>{t.scheduledTotal}</span><span className="font-medium">{formatCurrency(scheduledTotal, currencySymbol)}</span></div>
                                <Separator />
                                <div className={`flex justify-between font-semibold ${remainingAmount !== 0 ? 'text-red-600' : 'text-green-600'}`}>
                                    <span>{t.remainingAmount}</span>
                                    <span>{formatCurrency(remainingAmount, currencySymbol)}</span>
                                </div>
                            </div>
                            
                            {advanceForm.formState.errors.installments?.root && (
                                <p className="text-sm font-medium text-destructive">{advanceForm.formState.errors.installments.root.message || t.amountMismatchError}</p>
                            )}
                            
                            <div className="flex gap-2">
                                <Button type="submit" disabled={isPending}>
                                    {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                                    {t.saveAdvanceButton}
                                </Button>
                            </div>
                        </form>
                    </Form>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>{t.oneTimeTitle}</CardTitle>
                    <CardDescription>
                        {t.oneTimeDescription}
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <Form {...oneTimeForm}>
                        <form onSubmit={oneTimeForm.handleSubmit(onOneTimeSubmit)} className="space-y-6">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
                                <div className="sm:col-span-2">
                                    <FormField control={oneTimeForm.control} name="description" render={({ field }) => (
                                        <FormItem><FormLabel>{t.descriptionLabel}</FormLabel><FormControl><Input placeholder="e.g., Performance Bonus" {...field} /></FormControl><FormMessage /></FormItem>
                                    )} />
                                </div>
                                
                                <FormField control={oneTimeForm.control} name="amount" render={({ field }) => (
                                    <FormItem><FormLabel>{t.amountLabel}</FormLabel><FormControl><Input type="number" step="0.01" {...field} /></FormControl><FormMessage /></FormItem>
                                )} />
                                
                                <FormItem>
                                    <FormLabel>{t.month}</FormLabel>
                                    <div className="flex gap-2">
                                        <FormField control={oneTimeForm.control} name="month" render={({ field }) => (
                                            <Select onValueChange={field.onChange} defaultValue={field.value}><FormControl><SelectTrigger><SelectValue placeholder={t.month} /></SelectTrigger></FormControl>
                                                <SelectContent>{months.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
                                            </Select>
                                        )} />
                                        <FormField control={oneTimeForm.control} name="year" render={({ field }) => (
                                            <Select onValueChange={field.onChange} defaultValue={field.value}><FormControl><SelectTrigger><SelectValue placeholder={t.year} /></SelectTrigger></FormControl>
                                                <SelectContent>{years.map(y => <SelectItem key={y} value={y}>{y}</SelectItem>)}</SelectContent>
                                            </Select>
                                        )} />
                                    </div>
                                </FormItem>
                                
                                <div className="sm:col-span-2">
                                    <FormField control={oneTimeForm.control} name="recordType" render={({ field }) => (
                                        <FormItem className="space-y-3"><FormLabel>{t.recordTypeLabel}</FormLabel>
                                            <FormControl>
                                                <RadioGroup onValueChange={field.onChange} defaultValue={field.value} className="flex space-x-4">
                                                    <FormItem className="flex items-center space-x-2 space-y-0"><FormControl><RadioGroupItem value="deduction" /></FormControl><FormLabel className="font-normal">{t.deduction}</FormLabel></FormItem>
                                                    <FormItem className="flex items-center space-x-2 space-y-0"><FormControl><RadioGroupItem value="bonus" /></FormControl><FormLabel className="font-normal">{t.bonus}</FormLabel></FormItem>
                                                </RadioGroup>
                                            </FormControl>
                                        <FormMessage /></FormItem>
                                    )} />
                                </div>
                            </div>
                            <Button type="submit" disabled={isPending}>
                                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                                {t.addRecordButton}
                            </Button>
                        </form>
                    </Form>
                </CardContent>
            </Card>
       </div>
    );
}
