/* eslint-disable react-hooks/set-state-in-effect */
import { zodResolver } from '@hookform/resolvers/zod';
import { ComboboxDropdown } from '@ui/components/combobox-dropdown';
import { Button } from '@ui/components/ui/button';
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@ui/components/ui/form';
import { Input } from '@ui/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@ui/components/ui/select';
import { Textarea } from '@ui/components/ui/textarea';
import { Loader2 } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import * as z from 'zod';
import { FileUpload } from '@/components/common/FileUpload';
import { useAppText } from '@/lib/app-text';
import type { User } from '@/types';
import type { FundRequest, FundRequestFormData, Company, Bank, Branch, Department, Budget } from '@/types/fund-request';


interface FundRequestFormProps {
    fundRequest?: FundRequest;
    onSubmit: (data: FundRequestFormData) => void | Promise<void>;
    onCancel?: () => void;
    isSubmitting?: boolean;
    companies?: Company[];
    branches?: Branch[];
    departments?: Department[];
    budgets?: Budget[];
    employees?: User[];
    banks?: Bank[];
}

export function FundRequestForm({
    fundRequest,
    onSubmit,
    onCancel,
    isSubmitting = false,
    companies = [],
    branches = [],
    departments = [],
    employees = [],
    banks = [],
}: FundRequestFormProps) {
    const { t: text } = useAppText();

    const formSchema = useMemo(() => z.object({
        company_id: z.coerce.number().min(1, text('validation.required', { field: text('budget.field_company') })),
        branch_id: z.coerce.number().min(1, text('validation.required', { field: text('budget.field_branch') })),
        department_id: z.coerce.number().min(1, text('validation.required', { field: text('budget.field_department') })),
        applicant_id: z.coerce.number().min(1, text('validation.required', { field: text('fund_request.field_requester') })),
        description: z.string().min(1, text('validation.required', { field: text('fund_request.field_description') })),
        invoice_number: z.string().optional(),
        amount: z.coerce.number().min(1, text('validation.required', { field: text('fund_request.field_amount') })),
        account_name: z.string().min(1, text('validation.required', { field: text('fund_request.field_account_name') })),
        account_number: z.string().min(1, text('validation.required', { field: text('fund_request.field_account_number') })),
        bank_id: z.coerce.number().min(1, text('validation.required', { field: text('fund_request.field_bank') })),
        attachments: z.array(z.instanceof(File)).optional(),
    }), [text]);

    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: fundRequest
            ? {
                company_id: fundRequest.company_id,
                branch_id: fundRequest.branch_id,
                department_id: fundRequest.department_id,
                applicant_id: fundRequest.applicant_id,
                description: fundRequest.description,
                invoice_number: fundRequest.invoice_number || '',
                amount: fundRequest.amount,
                account_name: fundRequest.account_name,
                account_number: fundRequest.account_number,
                bank_id: fundRequest.bank_id,
            }
            : {
                company_id: 0,
                branch_id: 0,
                department_id: 0,
                applicant_id: 0,
                description: '',
                invoice_number: '',
                amount: 0,
                account_name: '',
                account_number: '',
                bank_id: 0,
                attachments: [],
            },
    });

    // Format number with thousands separator
    const formatCurrency = (value: string): string => {
        const numericValue = value.replace(/\D/g, '');

        return numericValue.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    };

    const selectedCompanyId = useWatch({
        control: form.control,
        name: 'company_id',
    });
    const normalizedCompanyId = Number(selectedCompanyId || 0);

    // Filter branches based on selected company
    const filteredBranches = normalizedCompanyId > 0
        ? branches.filter((branch) => Number(branch.company_id) === normalizedCompanyId)
        : branches;

    // Reset branch when company changes
    useEffect(() => {
        const currentBranch = form.getValues('branch_id');

        // Check if current branch belongs to new company
        if (currentBranch && !filteredBranches.some(b => b.id === currentBranch)) {
            form.setValue('branch_id', 0);
        }
    }, [filteredBranches, form]);

    // Local state for amount display
    const [amountDisplay, setAmountDisplay] = useState('');

    const amountValue = useWatch({
        control: form.control,
        name: 'amount',
    });

    // Sync amount display with form value on initial load or external change
    useEffect(() => {
        const amount = form.getValues('amount');

        if (amount) {
            setAmountDisplay(formatCurrency(amount.toString()));
        } else if (amount === 0) {
            setAmountDisplay('');
        }
    }, [amountValue, form]);

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                {/* Company & Applicant */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="company_id"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('budget.field_company')}</FormLabel>
                                <Select
                                    onValueChange={(value) => field.onChange(parseInt(value))}
                                    value={field.value ? field.value.toString() : ''}
                                >
                                    <FormControl>
                                        <SelectTrigger className="w-full">
                                            <SelectValue placeholder={text('fund_request.placeholder_select')} />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        {companies.map((company) => (
                                            <SelectItem key={company.id} value={company.id.toString()}>
                                                {company.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="applicant_id"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('fund_request.field_requester')}</FormLabel>
                                <FormControl>
                                    <ComboboxDropdown
                                        options={employees.map((employee: User) => ({
                                            label: employee.name,
                                            value: employee.id.toString(),
                                        }))}
                                        value={field.value ? field.value.toString() : ''}
                                        onValueChange={(value) => field.onChange(value ? parseInt(value) : 0)}
                                        placeholder={text('fund_request.placeholder_select')}
                                        searchPlaceholder={text('common.label_search')}
                                        disabled={employees.length === 0}
                                    />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                {/* Branch & Department */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="branch_id"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('budget.field_branch')}</FormLabel>
                                <Select
                                    onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                    value={field.value ? field.value.toString() : ''}
                                >
                                    <FormControl>
                                        <SelectTrigger className="w-full">
                                            <SelectValue placeholder={text('fund_request.placeholder_select')} />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        {filteredBranches.map((branch) => (
                                            <SelectItem key={branch.id} value={branch.id.toString()}>
                                                {branch.name}
                                            </SelectItem>
                                        ))}
                                        {filteredBranches.length === 0 && (
                                            <SelectItem value="__no_branch__" disabled>
                                                {text('fund_request.msg_no_branch_for_company')}
                                            </SelectItem>
                                        )}
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="department_id"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('budget.field_department')}</FormLabel>
                                <FormControl>
                                    <ComboboxDropdown
                                        options={departments.map((department: Department) => ({
                                            label: department.name,
                                            value: department.id.toString(),
                                        }))}
                                        value={field.value ? field.value.toString() : ''}
                                        onValueChange={(value) => field.onChange(value ? parseInt(value) : 0)}
                                        placeholder={text('fund_request.placeholder_select')}
                                        searchPlaceholder={text('common.label_search')}
                                        disabled={departments.length === 0}
                                    />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                {/* Description */}
                <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{text('fund_request.field_description')}</FormLabel>
                            <FormControl>
                                <Textarea
                                    placeholder={text('fund_request.placeholder_subject')}
                                    className="resize-none"
                                    rows={4}
                                    {...field}
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {/* Invoice Number */}
                    <FormField
                        control={form.control}
                        name="invoice_number"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('fund_request.field_invoice_number')}</FormLabel>
                                <FormControl>
                                    <Input placeholder={text('fund_request.placeholder_invoice')} {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    {/* Amount */}
                    <FormField
                        control={form.control}
                        name="amount"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('fund_request.field_amount')} (IDR)</FormLabel>
                                <FormControl>
                                    <Input
                                        type="text"
                                        placeholder="1.000.000"
                                        value={amountDisplay}
                                        onChange={(e) => {
                                            const val = e.target.value.replace(/[^0-9]/g, '');
                                            setAmountDisplay(val);
                                        }}
                                        onBlur={(e) => {
                                            const rawValue = e.target.value.replace(/\D/g, '');
                                            const numericValue = rawValue ? parseInt(rawValue) : 0;

                                            field.onChange(numericValue);
                                            setAmountDisplay(numericValue ? formatCurrency(numericValue.toString()) : '');
                                            field.onBlur();
                                        }}
                                    />
                                </FormControl>
                                <FormDescription>{text('fund_request.helper_amount')}</FormDescription>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                {/* Bank Account Information */}
                <div className="space-y-4 rounded-lg border p-4">
                    <h3 className="font-medium">{text('fund_request.section_bank_account')}</h3>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="account_name"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('fund_request.field_account_name')}</FormLabel>
                                    <FormControl>
                                        <Input placeholder="John Doe" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="account_number"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('fund_request.field_account_number')}</FormLabel>
                                    <FormControl>
                                        <Input placeholder="1234567890" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>

                    <FormField
                        control={form.control}
                        name="bank_id"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('fund_request.field_bank')}</FormLabel>
                                <FormControl>
                                    <ComboboxDropdown
                                        options={banks.map((bank: Bank) => ({
                                            label: bank.name,
                                            value: bank.id.toString(),
                                        }))}
                                        value={field.value ? field.value.toString() : ''}
                                        onValueChange={(value) => field.onChange(value ? parseInt(value) : 0)}
                                        placeholder={text('fund_request.placeholder_select')}
                                        searchPlaceholder={text('common.label_search')}
                                        disabled={banks.length === 0}
                                    />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <div />
                </div>

                {/* Attachments */}
                <FormField
                    control={form.control}
                    name="attachments"
                    render={({ field }) => (
                        <FormItem>
                            <FileUpload
                                label={text('fund_request.field_attachments')}
                                description={text('fund_request.helper_upload')}
                                multiple
                                maxSize={10 * 1024 * 1024} // 10MB
                                allowedExtensions={['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx']}
                                value={field.value || []}
                                onChange={field.onChange}
                                disabled={isSubmitting}
                            />
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {/* Submit Button */}
                <div className="flex justify-end gap-3">
                    {onCancel && (
                        <Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting}>
                            {text('common.btn_cancel')}
                        </Button>
                    )}
                    <Button type="submit" disabled={isSubmitting}>
                        {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                        {fundRequest ? text('form.btn_submit_update', { module: text('fund_request.title') }) : text('form.btn_submit_create', { module: text('fund_request.title') })}
                    </Button>
                </div>
            </form>
        </Form>
    );
}

