
"use client";

import { useTransition, useMemo } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { format, getYear, getMonth, addMonths } from "date-fns";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { useDocumentLock } from "@/hooks/use-document-lock";
import { DocumentLockBanner } from "@/components/admin/document-lock-banner";
import { handleApproveAndScheduleAdvance } from "@/lib/actions";
import { type LeaveRequest } from "@/lib/types";
import { Loader2 } from "lucide-react";
import { formatCurrency } from "@/lib/currency-formatter";

type Translation = {
  approveDialogTitle: string;
  approveDialogDescription: string;
  monthlyRepaymentLabel: string;
  repaymentStartLabel: string;
  month: string;
  year: string;
  repaymentPreviewTitle: string;
  repaymentPreviewDescription: string;
  confirmApproval: string;
  repaymentPreviewMonthlyPayment: string;
  repaymentPreviewNumPayments: string;
  repaymentPreviewStartDate: string;
}

type GlobalTranslation = {
    cancel: string;
}

const scheduleAdvanceSchema = z.object({
  requestId: z.string(),
  monthlyRepayment: z.coerce.number().min(1, "Monthly repayment amount must be greater than zero."),
  startMonth: z.string(),
  startYear: z.string(),
});

interface ApproveAdvanceDialogProps {
  request: LeaveRequest;
  onClose: () => void;
  t: Translation;
  tGlobal: GlobalTranslation;
  currencySymbol?: string;
}

export function ApproveAdvanceDialog({ request, onClose, t, tGlobal, currencySymbol = '$' }: ApproveAdvanceDialogProps) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const { lockStatus } = useDocumentLock('leave-request', request.id);
  const isEditLocked = lockStatus.isLocked;
  
  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 form = useForm<z.infer<typeof scheduleAdvanceSchema>>({
    resolver: zodResolver(scheduleAdvanceSchema),
    defaultValues: {
      requestId: request.id,
      monthlyRepayment: 100,
      startMonth: String(getMonth(addMonths(today, 1))),
      startYear: String(getYear(addMonths(today, 1))),
    },
  });

  const watchMonthlyRepayment = form.watch("monthlyRepayment");

  const installmentPreview = useMemo(() => {
    if (!request.amount || watchMonthlyRepayment <= 0) return null;

    const installmentsCount = Math.ceil(request.amount / watchMonthlyRepayment);
    const startDate = new Date(parseInt(form.getValues().startYear), parseInt(form.getValues().startMonth));

    return (
      <div className="mt-4 rounded-lg border p-4 bg-muted/50 space-y-2">
        <h4 className="font-semibold text-sm text-center mb-2">{t.repaymentPreviewTitle}</h4>
        <div className="flex justify-between items-center text-sm">
            <span className="text-muted-foreground">{t.repaymentPreviewMonthlyPayment}</span>
            <span className="font-bold">{formatCurrency(watchMonthlyRepayment, currencySymbol)}</span>
        </div>
        <div className="flex justify-between items-center text-sm">
            <span className="text-muted-foreground">{t.repaymentPreviewNumPayments}</span>
            <span className="font-bold">{installmentsCount}</span>
        </div>
        <div className="flex justify-between items-center text-sm">
            <span className="text-muted-foreground">{t.repaymentPreviewStartDate}</span>
            <span className="font-bold">{format(startDate, 'MMMM yyyy')}</span>
        </div>
      </div>
    );
  }, [watchMonthlyRepayment, request.amount, form, t]);

  async function onSubmit(values: z.infer<typeof scheduleAdvanceSchema>) {
    if (isEditLocked) { return; }
    startTransition(async () => {
      const result = await handleApproveAndScheduleAdvance(values);
      if (result?.success) {
        toast({ title: 'تمت الموافقة', description: result.message });
        onClose();
      } else {
        toast({ title: 'خطأ', description: result?.error || 'تعذر جدولة السلفة.', variant: 'destructive' });
      }
    });
  }

  return (
    <Dialog open={true} onOpenChange={onClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t.approveDialogTitle}</DialogTitle>
          <DialogDescription>
            {t.approveDialogDescription
                ? t.approveDialogDescription
                  .replace('{employeeName}', request.employeeName)
                  .replace('{amount}', request.amount?.toFixed(2) || '0')
                : ' '
            }
          </DialogDescription>
        </DialogHeader>
        <DocumentLockBanner lockStatus={lockStatus} />
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
             <div className="grid grid-cols-2 gap-4">
                <FormField control={form.control} name="monthlyRepayment" render={({ field }) => (
                    <FormItem>
                        <FormLabel>{t.monthlyRepaymentLabel}</FormLabel>
                        <FormControl><Input type="number" {...field} /></FormControl>
                        <FormMessage />
                    </FormItem>
                )} />
                
                <FormItem>
                    <FormLabel>{t.repaymentStartLabel}</FormLabel>
                    <div className="flex gap-2">
                        <FormField control={form.control} name="startMonth" 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={form.control} name="startYear" 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>

            {installmentPreview}

            <DialogFooter className="pt-4">
              <Button type="button" variant="outline" onClick={onClose}>{tGlobal.cancel}</Button>
              <Button type="submit" disabled={isPending || isEditLocked}>
                {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {t.confirmApproval}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
