import { useForm } from '@inertiajs/react';
import { useEffect } from 'react';
import { Badge } from '@/components/ui/badge';
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 { Switch } from '@/components/ui/switch';
import {
    Sheet,
    SheetClose,
    SheetContent,
    SheetDescription,
    SheetFooter,
    SheetHeader,
    SheetTitle,
} from '@/components/ui/sheet';
import type { AccountingDocumentTypeFormEntity } from '@/features/accounting-document-types/types';
import { useI18n } from '@/hooks/use-i18n';

type FormData = {
    name: string;
    sort_order: number;
    is_active: boolean;
};

type AccountingDocumentTypeFormSheetProps = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    mode: 'create' | 'edit';
    documentType: AccountingDocumentTypeFormEntity | null;
    onAfterSave: () => void;
};

const emptyForm: FormData = {
    name: '',
    sort_order: 0,
    is_active: true,
};

export function AccountingDocumentTypeFormSheet({
    open,
    onOpenChange,
    mode,
    documentType,
    onAfterSave,
}: AccountingDocumentTypeFormSheetProps) {
    const { t } = useI18n();
    const form = useForm<FormData>({ ...emptyForm });

    useEffect(() => {
        if (!open) {
            return;
        }

        if (mode === 'edit' && documentType) {
            form.setData({
                name: documentType.is_system ? '' : documentType.name,
                sort_order: documentType.sort_order,
                is_active: documentType.is_active,
            });

            return;
        }

        form.setData({ ...emptyForm });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, mode, documentType?.id]);

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

            return;
        }

        if (documentType) {
            form.patch(`/settings/accounting-document-types/${documentType.id}`, {
                preserveScroll: true,
                onSuccess: () => {
                    onAfterSave();
                },
            });
        }
    };

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

    const isSystemEdit = mode === 'edit' && documentType?.is_system;

    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">
                    {mode === 'edit' && documentType ? (
                        <div className="space-y-3 text-sm">
                            <div className="flex items-center gap-2">
                                <span className="text-muted-foreground">
                                    {t('settings.accounting_document_types.form.code_label')}:
                                </span>
                                <span className="font-mono text-xs">{documentType.code}</span>
                            </div>
                            {isSystemEdit ? (
                                <div className="rounded-md border bg-muted/30 px-3 py-2">
                                    <p className="text-xs text-muted-foreground">
                                        {t('settings.accounting_document_types.form.system_name_hint')}
                                    </p>
                                    <p className="mt-1 font-medium">{documentType.display_name}</p>
                                </div>
                            ) : null}
                            <div className="flex items-center gap-2">
                                <span className="text-muted-foreground">
                                    {t('settings.accounting_document_types.table.columns.status')}:
                                </span>
                                {documentType.is_active ? (
                                    <Badge variant="successSoft">
                                        {t('settings.accounting_document_types.table.status_active')}
                                    </Badge>
                                ) : (
                                    <Badge variant="secondary">
                                        {t('settings.accounting_document_types.table.status_inactive')}
                                    </Badge>
                                )}
                            </div>
                        </div>
                    ) : null}

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

                    <div className="space-y-2">
                        <Label htmlFor="adt-sort">{t('settings.accounting_document_types.form.sort_order_label')}</Label>
                        <Input
                            id="adt-sort"
                            type="number"
                            min={0}
                            max={65535}
                            value={form.data.sort_order}
                            onChange={(e) => form.setData('sort_order', Number.parseInt(e.target.value, 10) || 0)}
                            disabled={form.processing}
                        />
                        {form.errors.sort_order ? (
                            <p className="text-xs text-destructive">{form.errors.sort_order}</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="adt-active">
                                {mode === 'create'
                                    ? t('settings.accounting_document_types.form.active_on_create_label')
                                    : t('settings.accounting_document_types.form.active_label')}
                            </Label>
                            {mode === 'create' ? (
                                <p className="text-xs text-muted-foreground">
                                    {t('settings.accounting_document_types.form.active_on_create_hint')}
                                </p>
                            ) : null}
                        </div>
                        <Switch
                            id="adt-active"
                            checked={form.data.is_active}
                            onCheckedChange={(v) => form.setData('is_active', 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.accounting_document_types.form.discard')}
                        </Button>
                    </SheetClose>
                    <LoadingButton type="button" loading={form.processing} onClick={submit}>
                        {t('settings.accounting_document_types.form.save')}
                    </LoadingButton>
                </SheetFooter>
            </SheetContent>
        </Sheet>
    );
}
