import { useForm } from '@inertiajs/react';
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { LoadingButton } from '@/components/ui/loading-button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Sheet,
    SheetClose,
    SheetContent,
    SheetDescription,
    SheetFooter,
    SheetHeader,
    SheetTitle,
} from '@/components/ui/sheet';
import { Switch } from '@/components/ui/switch';
import type { AccountTypeOption, ChartOfAccountFormEntity } from '@/features/chart-of-accounts/types';
import { useI18n } from '@/hooks/use-i18n';

type FormData = {
    code: string;
    name: string;
    account_type: string;
    closed_marker: string;
    is_blocked: boolean;
};

type ChartOfAccountFormSheetProps = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    mode: 'create' | 'edit';
    account: ChartOfAccountFormEntity | null;
    accountTypeOptions: AccountTypeOption[];
    onAfterSave: () => void;
};

const emptyForm: FormData = {
    code: '',
    name: '',
    account_type: 'A',
    closed_marker: '',
    is_blocked: false,
};

export function ChartOfAccountFormSheet({
    open,
    onOpenChange,
    mode,
    account,
    accountTypeOptions,
    onAfterSave,
}: ChartOfAccountFormSheetProps) {
    const { t } = useI18n();
    const form = useForm<FormData>({ ...emptyForm });

    useEffect(() => {
        if (mode === 'edit' && account) {
            form.setData({
                code: account.code,
                name: account.name,
                account_type: account.account_type,
                closed_marker: account.closed_marker ?? '',
                is_blocked: account.is_blocked,
            });

            return;
        }

        form.setData({ ...emptyForm });
        // Mount-only: parent remounts this sheet when switching create/edit or reopening.
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const submit = () => {
        if (mode === 'create') {
            form.post('/settings/chart-of-accounts', {
                preserveScroll: true,
                onSuccess: () => {
                    form.reset();
                    onAfterSave();
                },
            });

            return;
        }

        if (account) {
            form.patch(`/settings/chart-of-accounts/${account.id}`, {
                preserveScroll: true,
                onSuccess: () => {
                    onAfterSave();
                },
            });
        }
    };

    const title = mode === 'create' ? t('settings.chart_of_accounts.form.create_title') : t('settings.chart_of_accounts.form.edit_title');
    const description =
        mode === 'create'
            ? t('settings.chart_of_accounts.form.create_description')
            : t('settings.chart_of_accounts.form.edit_description');

    return (
        <Sheet open={open} onOpenChange={onOpenChange}>
            <SheetContent className="flex w-full flex-col gap-0 overflow-y-auto sm:max-w-lg">
                <SheetHeader className="space-y-1 border-b px-6 py-4 text-left">
                    <SheetTitle>{title}</SheetTitle>
                    <SheetDescription>{description}</SheetDescription>
                </SheetHeader>

                <div className="flex flex-1 flex-col gap-4 px-6 py-4">
                    <div className="space-y-2">
                        <Label htmlFor="coa-code">{t('settings.chart_of_accounts.form.code_label')}</Label>
                        <Input
                            id="coa-code"
                            value={form.data.code}
                            onChange={(e) => form.setData('code', e.target.value)}
                            disabled={form.processing}
                            autoComplete="off"
                        />
                        {form.errors.code ? (
                            <p className="text-xs text-destructive">{form.errors.code}</p>
                        ) : null}
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor="coa-name">{t('settings.chart_of_accounts.form.name_label')}</Label>
                        <Input
                            id="coa-name"
                            value={form.data.name}
                            onChange={(e) => form.setData('name', e.target.value)}
                            disabled={form.processing}
                        />
                        {form.errors.name ? (
                            <p className="text-xs text-destructive">{form.errors.name}</p>
                        ) : null}
                    </div>

                    <div className="space-y-2">
                        <Label>{t('settings.chart_of_accounts.form.type_label')}</Label>
                        <Select
                            value={form.data.account_type}
                            onValueChange={(v) => form.setData('account_type', v)}
                            disabled={form.processing}
                        >
                            <SelectTrigger>
                                <SelectValue placeholder={t('settings.chart_of_accounts.form.type_placeholder')} />
                            </SelectTrigger>
                            <SelectContent>
                                {accountTypeOptions.map((opt) => (
                                    <SelectItem key={opt.value} value={opt.value}>
                                        {opt.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        {form.errors.account_type ? (
                            <p className="text-xs text-destructive">{form.errors.account_type}</p>
                        ) : null}
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor="coa-closed">{t('settings.chart_of_accounts.form.closed_marker_label')}</Label>
                        <Input
                            id="coa-closed"
                            value={form.data.closed_marker}
                            onChange={(e) => form.setData('closed_marker', e.target.value)}
                            disabled={form.processing}
                            placeholder={t('settings.chart_of_accounts.form.closed_marker_placeholder')}
                        />
                        {form.errors.closed_marker ? (
                            <p className="text-xs text-destructive">{form.errors.closed_marker}</p>
                        ) : null}
                    </div>

                    <div className="flex items-center justify-between rounded-lg border px-3 py-2">
                        <div className="space-y-0.5">
                            <Label htmlFor="coa-blocked">{t('settings.chart_of_accounts.form.blocked_label')}</Label>
                            <p className="text-xs text-muted-foreground">{t('settings.chart_of_accounts.form.blocked_hint')}</p>
                        </div>
                        <Switch
                            id="coa-blocked"
                            checked={form.data.is_blocked}
                            onCheckedChange={(v) => form.setData('is_blocked', v)}
                            disabled={form.processing}
                        />
                    </div>
                </div>

                <SheetFooter className="mt-auto flex-row justify-end gap-2 border-t px-6 py-4">
                    <SheetClose asChild>
                        <Button type="button" variant="outline" disabled={form.processing}>
                            {t('settings.chart_of_accounts.form.discard')}
                        </Button>
                    </SheetClose>
                    <LoadingButton type="button" loading={form.processing} onClick={submit}>
                        {t('settings.chart_of_accounts.form.save')}
                    </LoadingButton>
                </SheetFooter>
            </SheetContent>
        </Sheet>
    );
}
