/* 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, FormField, FormItem, FormLabel, FormMessage, FormDescription } 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 axios from 'axios';
import { useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import * as z from 'zod';
import { useAppText } from '@/lib/app-text';
import type { ChartOfAccount, ChartOfAccountFormData} from '@/types/finance';
import { ACCOUNT_TYPES, NORMAL_BALANCE_TYPES } from '@/types/finance';

const getFormSchema = (text: any) => z.object({
    code: z.string().min(1, text('validation.required', { field: text('chart_of_account.field_code') })).max(50),
    name: z.string().min(1, text('validation.required', { field: text('chart_of_account.field_name') })).max(255),
    type: z.enum(['asset', 'liability', 'equity', 'revenue', 'expense']),
    parent_id: z.number().optional().nullable(),
    normal_balance: z.enum(['debit', 'credit']),
    description: z.string().optional().nullable(),
    is_active: z.boolean(),
});

interface ChartOfAccountFormProps {
    account?: ChartOfAccount;
    parentAccount?: ChartOfAccount;
    onSubmit: (data: ChartOfAccountFormData) => void;
    isSubmitting: boolean;
    onCancel?: () => void;
}

export function ChartOfAccountForm({ account, parentAccount, onSubmit, isSubmitting, onCancel }: ChartOfAccountFormProps) {
    const { t: text } = useAppText();
    const schema = getFormSchema(text);
    type FormValues = z.infer<typeof schema>;

    const [parentAccounts, setParentAccounts] = useState<ChartOfAccount[]>([]);
    const [isLoadingParents, setIsLoadingParents] = useState(false);

    const form = useForm<FormValues>({
        resolver: zodResolver(schema) as any,
        defaultValues: {
            code: account?.code || '',
            name: account?.name || '',
            type: (account?.type || parentAccount?.type || 'asset') as FormValues['type'],
            parent_id: account?.parent_id || parentAccount?.id,
            normal_balance: (account?.normal_balance || 'debit') as FormValues['normal_balance'],
            description: account?.description || '',
            is_active: account?.is_active ?? true,
        },
    });

    const selectedType = useWatch({
        control: form.control,
        name: 'type',
    });

    // Load parent accounts based on type
    useEffect(() => {
        if (selectedType && !parentAccount) {
            setIsLoadingParents(true);

            axios.get(`/department/finance/chart-of-account/options?type=${selectedType}`)
                .then(res => {
                    // Filter out current account to prevent self-reference
                    const accounts = account
                        ? res.data.data.filter((a: ChartOfAccount) => a.id !== account.id)
                        : res.data.data;

                    setParentAccounts(accounts);
                    setIsLoadingParents(false);
                })
                .catch(() => {
                    setIsLoadingParents(false);
                });
        }
    }, [selectedType, account, parentAccount]);

    // Auto-set normal balance based on type
    useEffect(() => {
        if (!account) { // Only auto-set for new accounts
            const defaultBalance = ['asset', 'expense'].includes(selectedType) ? 'debit' : 'credit';

            form.setValue('normal_balance', defaultBalance);
        }
    }, [selectedType, account, form]);

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit((data: any) => onSubmit(data))} className="space-y-6">
                {parentAccount && (
                    <div className="rounded-lg border p-4 bg-muted/50">
                        <p className="text-sm font-medium">{text('chart_of_account.field_parent')}</p>
                        <p className="text-sm text-muted-foreground">
                            {parentAccount.code} - {parentAccount.name}
                        </p>
                    </div>
                )}

                <FormField
                    control={form.control}
                    name="code"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{text('chart_of_account.field_code')}</FormLabel>
                            <FormControl>
                                <Input placeholder={text('chart_of_account.placeholder_code')} {...field} />
                            </FormControl>
                            <FormDescription>
                                {text('drawer.create_description', { module: text('chart_of_account.field_code').toLowerCase() })}
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />

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

                <FormField
                    control={form.control}
                    name="type"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{text('chart_of_account.field_type')}</FormLabel>
                            <Select
                                onValueChange={field.onChange}
                                value={field.value?.toString()}
                                disabled={!!parentAccount}
                            >
                                <FormControl>
                                    <SelectTrigger className="w-full">
                                        <SelectValue placeholder={text('common.label_filter')} />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent className="w-[--radix-select-trigger-width]">
                                    {ACCOUNT_TYPES.map(type => (
                                        <SelectItem key={type.value} value={type.value}>
                                            {text(`chart_of_account.types.${type.value}`)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {!parentAccount && (
                    <FormField
                        control={form.control}
                        name="parent_id"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>{text('chart_of_account.field_parent')}</FormLabel>
                                <FormControl>
                                    <ComboboxDropdown
                                        options={parentAccounts.map((parent) => ({
                                            label: `${parent.code} - ${parent.name}`,
                                            value: parent.id.toString(),
                                        }))}
                                        value={field.value ? field.value.toString() : ''}
                                        onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                                        placeholder={text('common.label_filter')}
                                        searchPlaceholder={text('common.label_search')}
                                        emptyText={text('common.msg_no_data')}
                                        disabled={isLoadingParents}
                                        className="w-full"
                                    />
                                </FormControl>
                                <FormDescription>
                                    {text('drawer.create_description', { module: text('chart_of_account.field_parent').toLowerCase() })}
                                </FormDescription>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                )}

                <FormField
                    control={form.control}
                    name="normal_balance"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{text('chart_of_account.field_balance')}</FormLabel>
                            <Select
                                onValueChange={field.onChange}
                                value={field.value?.toString()}
                            >
                                <FormControl>
                                    <SelectTrigger className="w-full">
                                        <SelectValue placeholder={text('common.label_filter')} />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent className="w-[--radix-select-trigger-width]">
                                    {NORMAL_BALANCE_TYPES.map(type => (
                                        <SelectItem key={type.value} value={type.value}>
                                            {text(`chart_of_account.balances.${type.value}`)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <FormDescription>
                                {text('drawer.create_description', { module: text('chart_of_account.field_balance').toLowerCase() })}
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{text('chart_of_account.field_description')}</FormLabel>
                            <FormControl>
                                {(() => {
                                    const { value, ...fieldSansValue } = field;

                                    return (
                                        <Textarea
                                            placeholder={text('form.placeholder_description')}
                                            {...fieldSansValue}
                                            value={value ?? ''}
                                        />
                                    );
                                })()}
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

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

                <div className="flex justify-end gap-2">
                    {onCancel && (
                        <Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting}>
                            {text('common.btn_cancel')}
                        </Button>
                    )}
                    <Button type="submit" disabled={isSubmitting}>
                        {isSubmitting ? text('common.msg_loading') : account
                            ? text('form.btn_submit_update', { module: text('chart_of_account.title').toLowerCase() })
                            : text('form.btn_submit_create', { module: text('chart_of_account.title').toLowerCase() })}
                    </Button>
                </div>
            </form>
        </Form>
    );
}

