'use client';

import { useTransition, useMemo, useEffect } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { format, parseISO } from "date-fns";
import { ar } from 'date-fns/locale';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { CalendarIcon, PlusCircle, Trash2, Loader2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { cn } from "@/lib/utils";
import { handleProductionReportSubmit } from "@/lib/actions";
import { type Customer, type ProductionItem, type ProductionReport, type Employee } from "@/lib/types";
import { useRouter } from "next/navigation";
import { formatCurrency } from "@/lib/currency-formatter";


const productionFormSchema = z.object({
    date: z.date(),
    dailySales: z.coerce.number().optional().default(0),
    newDebts: z.array(z.object({ customerName: z.string().min(1, "Customer name is required."), amount: z.coerce.number().min(0.01) })).optional(),
    debtPayments: z.array(z.object({ customerId: z.string(), amount: z.coerce.number().min(0.01) })).optional(),
    consumedMaterials: z.array(z.object({ materialId: z.string(), value: z.coerce.number().min(0.01) })).optional(),
    expenses: z.array(z.object({ expenseId: z.string(), value: z.coerce.number().min(0.01) })).optional(),
    cashboxInventory: z.coerce.number().min(0, "Cashbox inventory cannot be negative."),
});

type ProductionFormProps = {
    t: any; // Translation object for Production section
    tGlobal: any;
    customers: Customer[];
    materials: ProductionItem[];
    expenses: ProductionItem[];
    user: Omit<Employee, 'password'>;
    initialData?: ProductionReport;
    selectedDate: Date;
    locale: string;
    currencySymbol?: string;
};

export default function ProductionForm({ t, tGlobal, customers, materials, expenses, user, initialData, selectedDate, locale, currencySymbol = '$' }: ProductionFormProps) {
    const [isPending, startTransition] = useTransition();
    const { toast } = useToast();
    const router = useRouter();

    const form = useForm<z.infer<typeof productionFormSchema>>({
        resolver: zodResolver(productionFormSchema),
        defaultValues: initialData ? {
            ...initialData,
            date: parseISO(initialData.date),
        } : {
            date: selectedDate,
            dailySales: 0,
            newDebts: [],
            debtPayments: [],
            consumedMaterials: [],
            expenses: [],
            cashboxInventory: 0,
        },
    });

    useEffect(() => {
        form.reset(initialData ? {
            ...initialData,
            date: parseISO(initialData.date),
        } : {
            date: selectedDate,
            dailySales: 0,
            newDebts: [],
            debtPayments: [],
            consumedMaterials: [],
            expenses: [],
            cashboxInventory: 0,
        });
    }, [initialData, selectedDate, form]);
    

    const { fields: newDebtFields, append: appendNewDebt, remove: removeNewDebt } = useFieldArray({ control: form.control, name: "newDebts" });
    const { fields: debtPaymentFields, append: appendDebtPayment, remove: removeDebtPayment } = useFieldArray({ control: form.control, name: "debtPayments" });
    const { fields: materialFields, append: appendMaterial, remove: removeMaterial } = useFieldArray({ control: form.control, name: "consumedMaterials" });
    const { fields: expenseFields, append: appendExpense, remove: removeExpense } = useFieldArray({ control: form.control, name: "expenses" });

    const watchDebtPayments = form.watch('debtPayments');
    const watchNewDebts = form.watch('newDebts');
    const watchConsumedMaterials = form.watch('consumedMaterials');
    const watchExpenses = form.watch('expenses');

    const totalDailyDebts = useMemo(() => (watchNewDebts || []).reduce((sum, item) => sum + (item.amount || 0), 0), [watchNewDebts]);
    const totalCollected = useMemo(() => (watchDebtPayments || []).reduce((sum, item) => sum + (item.amount || 0), 0), [watchDebtPayments]);
    const totalConsumption = useMemo(() => (watchConsumedMaterials || []).reduce((sum, item) => sum + (item.value || 0), 0), [watchConsumedMaterials]);
    const totalExpenses = useMemo(() => (watchExpenses || []).reduce((sum, item) => sum + (item.value || 0), 0), [watchExpenses]);
    
    // Auto-calculated daily sales
    const dailySales = totalCollected + totalConsumption - totalDailyDebts - totalExpenses;
    useEffect(() => {
        form.setValue('dailySales', dailySales);
    }, [dailySales, form]);

    async function onSubmit(values: z.infer<typeof productionFormSchema>) {
        startTransition(async () => {
            const result = await handleProductionReportSubmit({ ...values, date: format(values.date, 'yyyy-MM-dd')});
            if (result.success) {
                toast({ title: t?.reportSavedSuccess ?? "تم حفظ تقرير الإنتاج بنجاح.", description: "" });
                router.refresh();
            } else {
                toast({ title: t?.reportSavedError ?? "فشل حفظ تقرير الإنتاج.", description: result.error, variant: "destructive" });
            }
        });
    }

    const handleDateChange = (date: Date | undefined) => {
        if (date) {
            form.setValue('date', date);
            router.push(`/admin/production?date=${format(date, 'yyyy-MM-dd')}`);
        }
    }
    
    return (
        <Card>
            <CardHeader>
                <CardTitle>{t?.title ?? 'تقرير الإنتاج اليومي'}</CardTitle>
                <CardDescription>{(t?.description ?? 'سجل تفاصيل الإنتاج والمصاريف والديون لليوم المحدد. التقرير مقدم من {user}.').replace('{user}', user.name)}</CardDescription>
            </CardHeader>
            <CardContent>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">

                        <FormField control={form.control} name="date" render={({ field }) => (
                            <FormItem className="flex flex-col"><FormLabel>{t?.reportDate ?? 'تاريخ التقرير'}</FormLabel>
                                <Popover><PopoverTrigger asChild>
                                    <FormControl><Button variant={'outline'} className={cn("w-[240px] ps-3 text-start font-normal", !field.value && "text-muted-foreground")}>
                                        {field.value ? format(field.value, 'PPP', {locale: locale === 'ar' ? ar : undefined}) : <span>Pick a date</span>}
                                        <CalendarIcon className="ms-auto h-4 w-4 opacity-50" />
                                    </Button></FormControl>
                                </PopoverTrigger><PopoverContent className="w-auto p-0" align="start">
                                    <Calendar mode="single" selected={field.value} onSelect={handleDateChange} initialFocus />
                                </PopoverContent></Popover><FormMessage /></FormItem>
                        )} />

                        {/* Daily Sales (Readonly) */}
                        <Card><CardHeader><CardTitle>{t?.salesTitle ?? 'قيمة المبيعات اليومية'}</CardTitle><CardDescription>{t?.salesDescription ?? 'يتم حسابه تلقائيًا بناءً على الأقسام الأخرى.'}</CardDescription></CardHeader>
                            <CardContent>
                                <FormField control={form.control} name="dailySales" render={({ field }) => (
                                    <FormItem><FormLabel>Total Sales</FormLabel><FormControl><Input type="number" {...field} readOnly className="font-bold text-lg bg-muted" /></FormControl><FormMessage /></FormItem>
                                )} />
                            </CardContent>
                        </Card>

                        {/* New Debts */}
                        <Card><CardHeader><CardTitle>{t?.debtsTitle ?? 'قيمة الديون اليومية'}</CardTitle><CardDescription>{t?.debtsDescription ?? 'إضافة الديون الجديدة التي تم إنشاؤها اليوم.'}</CardDescription></CardHeader>
                            <CardContent className="space-y-4">
                                {newDebtFields.map((field, index) => (
                                    <div key={field.id} className="flex gap-2 items-start">
                                        <FormField control={form.control} name={`newDebts.${index}.customerName`} render={({ field }) => (
                                            <FormItem className="flex-1"><FormLabel className="sr-only">{t?.debtCustomerName ?? 'اسم العميل'}</FormLabel><FormControl><Input placeholder={t?.debtCustomerName ?? 'اسم العميل'} {...field} /></FormControl><FormMessage /></FormItem>
                                        )} />
                                        <FormField control={form.control} name={`newDebts.${index}.amount`} render={({ field }) => (
                                            <FormItem><FormLabel className="sr-only">{t?.debtAmount ?? 'مبلغ الدين'}</FormLabel><FormControl><Input type="number" placeholder={t?.debtAmount ?? 'مبلغ الدين'} {...field} /></FormControl><FormMessage /></FormItem>
                                        )} />
                                        <Button type="button" variant="ghost" size="icon" onClick={() => removeNewDebt(index)}><Trash2 className="h-4 w-4" /></Button>
                                    </div>
                                ))}
                                <Button type="button" variant="outline" size="sm" onClick={() => appendNewDebt({ customerName: '', amount: 0 })}><PlusCircle className="me-2" />{t?.addDebt ?? 'إضافة دين'}</Button>
                                <Separator />
                                <div className="flex justify-between font-medium"><span>{t?.totalDailyDebts ?? 'إجمالي الديون اليومية'}</span><span>{formatCurrency(totalDailyDebts, currencySymbol)}</span></div>
                            </CardContent>
                        </Card>

                        {/* Debt Payments */}
                        <Card><CardHeader><CardTitle>{t?.debtCollectionTitle ?? 'تحصيل ديون سابقة'}</CardTitle><CardDescription>{t?.debtCollectionDescription ?? 'تسجيل المبالغ المحصلة من ديون العملاء السابقة.'}</CardDescription></CardHeader>
                            <CardContent className="space-y-4">
                               {debtPaymentFields.map((field, index) => (
                                    <div key={field.id} className="flex gap-2 items-start">
                                         <FormField control={form.control} name={`debtPayments.${index}.customerId`} render={({ field }) => (
                                            <FormItem className="flex-1">
                                                <FormLabel className="sr-only">{t?.selectCustomer ?? 'اختر عميلاً...'}</FormLabel>
                                                <Select onValueChange={field.onChange} defaultValue={field.value}>
                                                    <FormControl><SelectTrigger><SelectValue placeholder={t?.selectCustomer ?? 'اختر عميلاً...'} /></SelectTrigger></FormControl>
                                                    <SelectContent>{customers.map(c => <SelectItem key={c.id} value={c.id}>{c.name} (Balance: {formatCurrency(c.balance, currencySymbol)})</SelectItem>)}</SelectContent>
                                                </Select>
                                            </FormItem>
                                         )} />
                                         <FormField control={form.control} name={`debtPayments.${index}.amount`} render={({ field }) => (
                                            <FormItem><FormLabel className="sr-only">{t?.paymentAmount ?? 'المبلغ المدفوع'}</FormLabel><FormControl><Input type="number" placeholder={t?.paymentAmount ?? 'المبلغ المدفوع'} {...field} /></FormControl><FormMessage /></FormItem>
                                         )} />
                                         <Button type="button" variant="ghost" size="icon" onClick={() => removeDebtPayment(index)}><Trash2 className="h-4 w-4" /></Button>
                                    </div>
                               ))}
                                <Button type="button" variant="outline" size="sm" onClick={() => appendDebtPayment({ customerId: '', amount: 0 })}><PlusCircle className="me-2" />{t?.addPayment ?? 'إضافة دفعة'}</Button>
                                <Separator />
                                <div className="flex justify-between font-medium"><span>{t?.totalCollected ?? 'إجمالي المحصل'}</span><span>{formatCurrency(totalCollected, currencySymbol)}</span></div>
                            </CardContent>
                        </Card>

                        {/* Consumed Materials */}
                        <Card><CardHeader><CardTitle>{t?.consumptionTitle ?? 'المواد المستهلكة'}</CardTitle><CardDescription>{t?.consumptionDescription ?? 'سجل قيمة المواد المستخدمة في الإنتاج اليومي.'}</CardDescription></CardHeader>
                            <CardContent className="space-y-4">
                                {materialFields.map((field, index) => (
                                    <div key={field.id} className="flex gap-2 items-start">
                                        <FormField control={form.control} name={`consumedMaterials.${index}.materialId`} render={({ field }) => (
                                            <FormItem className="flex-1"><FormLabel className="sr-only">{t?.selectMaterial ?? 'اختر مادة...'}</FormLabel>
                                                <Select onValueChange={field.onChange} defaultValue={field.value}>
                                                    <FormControl><SelectTrigger><SelectValue placeholder={t?.selectMaterial ?? 'اختر مادة...'} /></SelectTrigger></FormControl>
                                                    <SelectContent>{materials.map(m => <SelectItem key={m.id} value={m.id}>{m.name}</SelectItem>)}</SelectContent>
                                                </Select>
                                            </FormItem>
                                        )} />
                                        <FormField control={form.control} name={`consumedMaterials.${index}.value`} render={({ field }) => (
                                            <FormItem><FormLabel className="sr-only">{t?.materialValue ?? 'قيمة المادة'}</FormLabel><FormControl><Input type="number" placeholder={t?.materialValue ?? 'قيمة المادة'} {...field} /></FormControl><FormMessage /></FormItem>
                                        )} />
                                        <Button type="button" variant="ghost" size="icon" onClick={() => removeMaterial(index)}><Trash2 className="h-4 w-4" /></Button>
                                    </div>
                                ))}
                                <Button type="button" variant="outline" size="sm" onClick={() => appendMaterial({ materialId: '', value: 0 })}><PlusCircle className="me-2" />{t?.addMaterial ?? 'إضافة مادة'}</Button>
                                <Separator />
                                <div className="flex justify-between font-medium"><span>{t?.totalConsumption ?? 'إجمالي الاستهلاك'}</span><span>{formatCurrency(totalConsumption, currencySymbol)}</span></div>
                            </CardContent>
                        </Card>

                        {/* Expenses */}
                        <Card><CardHeader><CardTitle>{t?.expensesTitle ?? 'المصاريف'}</CardTitle><CardDescription>{t?.expensesDescription ?? 'تسجيل جميع المصاريف التشغيلية الأخرى. المصاريف المرتبطة بمشروع عقاري تُرحّل تلقائياً إلى حساب المشروع.'}</CardDescription></CardHeader>
                            <CardContent className="space-y-4">
                                {expenseFields.map((field, index) => (
                                    <div key={field.id} className="flex gap-2 items-start">
                                        <FormField control={form.control} name={`expenses.${index}.expenseId`} render={({ field }) => (
                                            <FormItem className="flex-1"><FormLabel className="sr-only">{t?.selectExpense ?? 'اختر مصروفًا...'}</FormLabel>
                                                <Select onValueChange={field.onChange} defaultValue={field.value}>
                                                    <FormControl><SelectTrigger><SelectValue placeholder={t?.selectExpense ?? 'اختر مصروفًا...'} /></SelectTrigger></FormControl>
                                                    <SelectContent>{expenses.map(e => <SelectItem key={e.id} value={e.id}>{e.name}{e.realEstateProjectId ? ' • مشروع عقاري' : ''}</SelectItem>)}</SelectContent>
                                                </Select>
                                            </FormItem>
                                        )} />
                                        <FormField control={form.control} name={`expenses.${index}.value`} render={({ field }) => (
                                            <FormItem><FormLabel className="sr-only">{t?.expenseValue ?? 'قيمة المصروف'}</FormLabel><FormControl><Input type="number" placeholder={t?.expenseValue ?? 'قيمة المصروف'} {...field} /></FormControl><FormMessage /></FormItem>
                                        )} />
                                        <Button type="button" variant="ghost" size="icon" onClick={() => removeExpense(index)}><Trash2 className="h-4 w-4" /></Button>
                                    </div>
                                ))}
                                <Button type="button" variant="outline" size="sm" onClick={() => appendExpense({ expenseId: '', value: 0 })}><PlusCircle className="me-2" />{t?.addExpense ?? 'إضافة مصروف'}</Button>
                                <Separator />
                                <div className="flex justify-between font-medium"><span>{t?.totalExpenses ?? 'إجمالي المصاريف'}</span><span>{formatCurrency(totalExpenses, currencySymbol)}</span></div>
                            </CardContent>
                        </Card>

                        {/* Cashbox */}
                        <Card><CardHeader><CardTitle>{t?.cashboxTitle ?? 'جرد الصندوق اليومي'}</CardTitle><CardDescription>{t?.cashboxDescription ?? 'أدخل المبلغ النقدي الفعلي الموجود في الصندوق بنهاية اليوم.'}</CardDescription></CardHeader>
                            <CardContent>
                                <FormField control={form.control} name="cashboxInventory" render={({ field }) => (
                                    <FormItem><FormLabel>{t?.cashboxAmount ?? 'المبلغ في الصندوق'}</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
                                )} />
                            </CardContent>
                        </Card>

                        <Button type="submit" disabled={isPending}>
                            {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                            {t?.saveReport ?? 'حفظ التقرير'}
                        </Button>
                    </form>
                </Form>
            </CardContent>
        </Card>
    );
}
