import { zodResolver } from '@hookform/resolvers/zod';
import { ComboboxDropdown } from '@ui/components/combobox-dropdown';
import { DatePicker } from '@ui/components/date-picker';
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 { Switch } from '@ui/components/ui/switch';
import { Textarea } from '@ui/components/ui/textarea';
import { Loader2 } from 'lucide-react';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { useAppText } from '@/lib/app-text';
import type { Budget, BudgetFormData } from '@/types/finance';

const getBudgetFormSchema = (text: any) => z.object({
    name: z.string().min(1, text('validation.required', { field: text('budget.field_name') })),
    description: z.string().optional(),
    period_year: z.number().int().min(2000, text('validation.required', { field: text('budget.field_year') })),
    period_month: z.number().int().min(1).max(12).optional(),
    company_id: z.number().int().optional(),
    branch_id: z.number().int().optional(),
    department_id: z.number().int().optional(),
    coa_id: z.number().int().optional(),
    source_account_id: z.number().int().optional(),
    allocated_amount: z.number().min(0, text('validation.required', { field: text('budget.field_amount') })),
    start_date: z.string().optional(),
    end_date: z.string().optional(),
    is_active: z.boolean(),
}) satisfies z.ZodType<BudgetFormData>;

interface BudgetFormProps {
    budget?: Budget;
    onSubmit: (data: BudgetFormData) => void | Promise<void>;
    isSubmitting?: boolean;
    onCancel?: () => void;
    companies?: Array<{ id: number; name: string }>;
    branches?: Array<{ id: number; name: string }>;
    departments?: Array<{ id: number; name: string }>;
    chartOfAccounts?: Array<{ id: number; code: string; name: string }>;
    sourceAccounts?: Array<{ id: number; name: string }>;
}

export function BudgetForm({
    budget,
    onSubmit,
    isSubmitting = false,
    onCancel,
    companies = [],
    branches = [],
    departments = [],
    chartOfAccounts = [],
    sourceAccounts = [],
}: BudgetFormProps) {
    const { t: text } = useAppText();
    const schema = getBudgetFormSchema(text);
    const farFutureMaxDate = new Date('2099-12-31');

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

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

    const formatDateToLocalString = (date: Date | undefined): string => {
        if (!date) {
return '';
}

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        return `${year}-${month}-${day}`;
    };

    const parseLocalDate = (dateStr: any): Date | undefined => {
        if (!dateStr) {
return undefined;
}

        if (dateStr instanceof Date) {
return dateStr;
}

        const parts = String(dateStr).split('-');

        if (parts.length === 3) {
            const [year, month, day] = parts.map(Number);

            return new Date(year, month - 1, day);
        }

        const d = new Date(dateStr);

        return isNaN(d.getTime()) ? undefined : d;
    };

    const form = useForm<BudgetFormData>({
        resolver: zodResolver(schema) as any,
        defaultValues: {
            name: budget?.name || '',
            description: budget?.description || '',
            period_year: budget?.period_year || new Date().getFullYear(),
            period_month: budget?.period_month || undefined,
            company_id: budget?.company_id || undefined,
            branch_id: budget?.branch_id || undefined,
            department_id: budget?.department_id || undefined,
            coa_id: budget?.coa_id || undefined,
            source_account_id: budget?.source_account_id || undefined,
            allocated_amount: budget?.allocated_amount || 0,
            start_date: budget?.start_date || '',
            end_date: budget?.end_date || '',
            is_active: budget?.is_active ?? true,
        },
    });

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                {/* Basic Information */}
                <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-foreground">{text('budget.section_basic_info')}</h3>

                    {/* Name */}
                    <FormField
                        control={form.control}
                        name="name"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('budget.field_name')} *</FormLabel>
                                <FormControl>
                                    <Input placeholder={text('budget.placeholder_budget_name')} {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    {/* Description */}
                    <FormField
                        control={form.control}
                        name="description"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('budget.field_description')}</FormLabel>
                                <FormControl>
                                    <Textarea
                                        placeholder={text('budget.placeholder_budget_description')}
                                        rows={3}
                                        {...field}
                                    />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                {/* Period */}
                <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-foreground">{text('budget.section_period')}</h3>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {/* Period Year */}
                        <FormField
                            control={form.control}
                            name="period_year"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('budget.field_year')} *</FormLabel>
                                    <FormControl>
                                        <Input
                                            type="number"
                                            placeholder="2024"
                                            value={field.value || ''}
                                            onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                                            onBlur={field.onBlur}
                                            name={field.name}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* Period Month */}
                        <FormField
                            control={form.control}
                            name="period_month"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('budget.field_month_optional')}</FormLabel>
                                    <Select
                                        onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                        value={field.value?.toString() || ''}
                                    >
                                        <FormControl>
                                            <SelectTrigger className="w-full">
                                                <SelectValue placeholder={text('budget.placeholder_select_month')} />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value="1">{text('budget.month_january')}</SelectItem>
                                            <SelectItem value="2">{text('budget.month_february')}</SelectItem>
                                            <SelectItem value="3">{text('budget.month_march')}</SelectItem>
                                            <SelectItem value="4">{text('budget.month_april')}</SelectItem>
                                            <SelectItem value="5">{text('budget.month_may')}</SelectItem>
                                            <SelectItem value="6">{text('budget.month_june')}</SelectItem>
                                            <SelectItem value="7">{text('budget.month_july')}</SelectItem>
                                            <SelectItem value="8">{text('budget.month_august')}</SelectItem>
                                            <SelectItem value="9">{text('budget.month_september')}</SelectItem>
                                            <SelectItem value="10">{text('budget.month_october')}</SelectItem>
                                            <SelectItem value="11">{text('budget.month_november')}</SelectItem>
                                            <SelectItem value="12">{text('budget.month_december')}</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>
                </div>

                {/* Organization */}
                <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-foreground">{text('budget.section_organization')}</h3>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {/* Company */}
                        {companies.length > 0 && (
                            <FormField
                                control={form.control}
                                name="company_id"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>{text('budget.field_company')}</FormLabel>
                                        <Select
                                            onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                            value={field.value?.toString() || ''}
                                        >
                                            <FormControl>
                                                <SelectTrigger className="w-full">
                                                    <SelectValue placeholder={text('budget.placeholder_select_company')} />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {companies.map((company) => (
                                                    <SelectItem key={company.id} value={company.id.toString()}>
                                                        {company.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        )}

                        {/* Branch */}
                        {branches.length > 0 && (
                            <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?.toString() || ''}
                                        >
                                            <FormControl>
                                                <SelectTrigger className="w-full">
                                                    <SelectValue placeholder={text('budget.placeholder_select_branch')} />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {branches.map((branch) => (
                                                    <SelectItem key={branch.id} value={branch.id.toString()}>
                                                        {branch.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        )}

                        {/* Department */}
                        {departments.length > 0 && (
                            <FormField
                                control={form.control}
                                name="department_id"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>{text('budget.field_department')}</FormLabel>
                                        <Select
                                            onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                            value={field.value?.toString() || ''}
                                        >
                                            <FormControl>
                                                <SelectTrigger className="w-full">
                                                    <SelectValue placeholder={text('budget.placeholder_select_department')} />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {departments.map((dept) => (
                                                    <SelectItem key={dept.id} value={dept.id.toString()}>
                                                        {dept.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        )}

                        {/* Chart of Account */}
                        <FormField
                            control={form.control}
                            name="coa_id"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('budget.field_coa')}</FormLabel>
                                    <ComboboxDropdown
                                        options={chartOfAccounts.map((coa) => ({
                                            label: `${coa.code} - ${coa.name}`,
                                            value: coa.id.toString(),
                                        }))}
                                        value={field.value?.toString()}
                                        onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                        placeholder={
                                            chartOfAccounts.length > 0
                                                ? text('budget.placeholder_select_coa')
                                                : 'No chart of account available'
                                        }
                                        searchPlaceholder={text('budget.placeholder_search_coa')}
                                        emptyText={text('common.msg_no_data')}
                                        disabled={chartOfAccounts.length === 0}
                                        className="w-full"
                                    />
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        {/* Source Account */}
                        {sourceAccounts.length > 0 && (
                            <FormField
                                control={form.control}
                                name="source_account_id"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>{text('budget.field_source_account')}</FormLabel>
                                        <Select
                                            onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                            value={field.value?.toString() || ''}
                                        >
                                            <FormControl>
                                                <SelectTrigger className="w-full">
                                                    <SelectValue placeholder={text('budget.placeholder_select_source_account')} />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {sourceAccounts.map((sa) => (
                                                    <SelectItem key={sa.id} value={sa.id.toString()}>
                                                        {sa.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        )}
                    </div>
                </div>

                {/* Budget Amount */}
                <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-foreground">{text('budget.section_amount')}</h3>

                    <FormField
                        control={form.control}
                        name="allocated_amount"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('budget.field_amount')} *</FormLabel>
                                <FormControl>
                                    <Input
                                        type="text"
                                        placeholder={text('budget.placeholder_amount')}
                                        value={field.value ? formatCurrency(field.value.toString()) : ''}
                                        onChange={(e) => {
                                            const val = e.target.value.replace(/\D/g, '');
                                            field.onChange(val ? parseInt(val) : 0);
                                        }}
                                    />
                                </FormControl>
                                <FormDescription>{text('budget.helper_amount_idr')}</FormDescription>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                {/* Date Range */}
                <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-foreground">{text('budget.section_validity')}</h3>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="start_date"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('budget.field_start_date')}</FormLabel>
                                    <FormControl>
                                            <DatePicker
                                                selected={parseLocalDate(field.value)}
                                                onSelect={(date) => field.onChange(formatDateToLocalString(date))}
                                                placeholder={text('budget.field_start_date')}
                                                className="w-full"
                                                buttonClassName="w-full"
                                                maxDate={farFutureMaxDate}
                                            />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="end_date"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{text('budget.field_end_date')}</FormLabel>
                                    <FormControl>
                                            <DatePicker
                                                selected={parseLocalDate(field.value)}
                                                onSelect={(date) => field.onChange(formatDateToLocalString(date))}
                                                placeholder={text('budget.field_end_date')}
                                                className="w-full"
                                                buttonClassName="w-full"
                                                maxDate={farFutureMaxDate}
                                            />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>
                </div>

                {/* Status */}
                <div className="space-y-4">
                    <h3 className="text-lg font-semibold text-foreground">{text('budget.section_status')}</h3>

                    <FormField
                        control={form.control}
                        name="is_active"
                        render={({ field }) => (
                            <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                                <div className="space-y-0.5">
                                    <FormLabel className="text-base text-foreground">{text('budget.field_active_status')}</FormLabel>
                                    <FormDescription>
                                        {text('budget.helper_active_status')}
                                    </FormDescription>
                                </div>
                                <FormControl>
                                    <Switch
                                        checked={field.value}
                                        onCheckedChange={field.onChange}
                                    />
                                </FormControl>
                            </FormItem>
                        )}
                    />
                </div>

                {/* Submit Button */}
                <div className="flex justify-end gap-2 pt-4">
                    {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" />
                                {text('common.status_saving')}
                            </>
                        ) : (
                            budget
                                ? text('form.btn_submit_update', { module: text('budget.title') })
                                : text('form.btn_submit_create', { module: text('budget.title') })
                        )}
                    </Button>
                </div>
            </form>
        </Form>
    );
}

