import { useForm } from '@inertiajs/react';
import { Banknote, Package, Plus, Save, Trash2 } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { ConfirmActionDialog } from '@/components/confirm-action-dialog';
import { AppDateInput } from '@/components/ui/app-date-input';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardFooter,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ProductSearchSelect } from '@/components/ui/product-search-select';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { useLanguage } from '@/contexts/language-context';
import { advanceProductLineTotal } from '@/lib/advance-amounts';
import { formatEmployeeJoiningDateOrDash, formatMoneyAmountOrDash, formatQuantityOrDash } from '@/lib/dates';
import { cn } from '@/lib/utils';
import { zodErrorToFieldMap } from '@/lib/zod-errors';
import { buildPermanentEmployeeAdvanceSchema } from '@/validation/schemas';

/**
 * @returns {{
 *   factory_product_id: string,
 *   quantity_mode: 'pack'|'weight',
 *   quantity: string,
 *   total_weight: string,
 *   weight_price: string,
 * }}
 */
function emptyProductDraft() {
    return {
        factory_product_id: '',
        quantity_mode: 'pack',
        quantity: '',
        total_weight: '',
        weight_price: '',
    };
}

/**
 * @param {object} props
 * @param {'create'|'edit'} props.mode
 * @param {object} [props.initial]
 * @param {Array<{id: number, full_name: string, designation_name?: string}>} props.employees
 * @param {Array<{id: number, name: string, unit_name?: string, stock_on_hand?: string}>} props.products
 * @param {string} props.submitUrl
 * @param {'post'|'put'} props.submitMethod
 * @param {Record<string, string>} props.labels
 * @param {string} props.submitLabel
 * @param {string} props.submittingLabel
 * @param {string} props.confirmTitle
 * @param {string} props.confirmBody
 * @param {string} props.cancelLabel
 */
export function PermanentEmployeeAdvanceForm({
    mode,
    initial,
    employees,
    products,
    submitUrl,
    submitMethod,
    labels,
    submitLabel,
    submittingLabel,
    confirmTitle,
    confirmBody,
    cancelLabel,
}) {
    const { t, locale } = useLanguage();
    const v = t.validation;
    const schema = useMemo(() => buildPermanentEmployeeAdvanceSchema(v), [v]);
    const [confirmOpen, setConfirmOpen] = useState(false);
    const [draft, setDraft] = useState(emptyProductDraft);
    const [draftErrors, setDraftErrors] = useState({});
    const [items, setItems] = useState([]);

    const form = useForm({
        permanent_employee_id: initial?.permanent_employee_id
            ? String(initial.permanent_employee_id)
            : '',
        type: initial?.type ?? 'cash',
        advance_date: initial?.advance_date ?? '',
        amount: initial?.amount ?? '',
        factory_product_id: initial?.factory_product_id
            ? String(initial.factory_product_id)
            : '',
        quantity_mode: initial?.quantity_mode ?? 'pack',
        quantity: initial?.quantity ?? '',
        total_weight: initial?.total_weight ?? '',
        weight_price: initial?.weight_price ?? '',
        notes: initial?.notes ?? '',
        items: [],
    });

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

        form.setData({
            permanent_employee_id: initial.permanent_employee_id
                ? String(initial.permanent_employee_id)
                : '',
            type: initial.type ?? 'cash',
            advance_date: initial.advance_date ?? '',
            amount: initial.amount ?? '',
            factory_product_id: initial.factory_product_id
                ? String(initial.factory_product_id)
                : '',
            quantity_mode: initial.quantity_mode ?? 'weight',
            quantity: initial.quantity ?? '',
            total_weight: initial.total_weight ?? '',
            weight_price: initial.weight_price ?? '',
            notes: initial.notes ?? '',
            items: [],
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps -- Inertia form identity is unstable
    }, [initial]);

    const isProduct = form.data.type === 'product';
    const isCreate = mode === 'create';

    const selectedEmployee = useMemo(
        () =>
            employees.find(
                (employee) => String(employee.id) === String(form.data.permanent_employee_id),
            ) ?? null,
        [employees, form.data.permanent_employee_id],
    );

    const productAmountPreview = useMemo(() => {
        if (isCreate && isProduct) {
            return items.reduce(
                (sum, item) => sum + advanceProductLineTotal(item),
                0,
            );
        }

        return advanceProductLineTotal({
            quantity_mode: form.data.quantity_mode,
            quantity: form.data.quantity,
            total_weight: form.data.total_weight,
            weight_price: form.data.weight_price,
        });
    }, [
        isCreate,
        isProduct,
        items,
        form.data.quantity_mode,
        form.data.quantity,
        form.data.total_weight,
        form.data.weight_price,
    ]);

    const selectedProduct = useMemo(() => {
        const productId = isCreate && isProduct
            ? draft.factory_product_id
            : form.data.factory_product_id;

        return (
            products.find((product) => String(product.id) === String(productId)) ?? null
        );
    }, [isCreate, isProduct, draft.factory_product_id, form.data.factory_product_id, products]);

    function formatProductLabel(product) {
        const name = product.unit_name ? `${product.name} (${product.unit_name})` : product.name;
        const stock = formatQuantityOrDash(product.stock_on_hand, locale);

        return `${name} · ${labels.colStock}: ${stock}`;
    }

    function productName(productId) {
        return products.find((product) => String(product.id) === String(productId))?.name ?? '—';
    }

    const displayAmount = isProduct ? productAmountPreview : form.data.amount;

    function setAdvanceType(type) {
        form.setData((data) => ({
            ...data,
            type,
            ...(type === 'cash'
                ? {
                      factory_product_id: '',
                      quantity_mode: 'pack',
                      quantity: '',
                      total_weight: '',
                      weight_price: '',
                      items: [],
                  }
                : { amount: '' }),
        }));
        setItems([]);
        setDraft(emptyProductDraft());
        setDraftErrors({});
        form.clearErrors(
            type === 'cash'
                ? [
                      'factory_product_id',
                      'quantity_mode',
                      'quantity',
                      'total_weight',
                      'weight_price',
                      'items',
                  ]
                : ['amount'],
        );
    }

    function updateDraft(field, value) {
        setDraft((current) => ({ ...current, [field]: value }));
        setDraftErrors((current) => {
            if (!current[field]) {
                return current;
            }

            const next = { ...current };
            delete next[field];

            return next;
        });
    }

    function reservedPacksForProduct(productId, excludeKey = null) {
        return items.reduce((sum, item) => {
            if (excludeKey && item.key === excludeKey) {
                return sum;
            }

            if (String(item.factory_product_id) !== String(productId)) {
                return sum;
            }

            const packs = Number(item.quantity);

            return sum + (Number.isFinite(packs) && packs > 0 ? packs : 0);
        }, 0);
    }

    function availablePacksForProduct(productId) {
        const product = products.find((entry) => String(entry.id) === String(productId));
        const onHand = Number(product?.stock_on_hand);
        const base = Number.isFinite(onHand) ? onHand : 0;
        const credit =
            mode === 'edit' &&
            initial?.type === 'product' &&
            String(initial?.factory_product_id) === String(productId)
                ? Number(initial?.quantity) || 0
                : 0;

        return Math.max(0, base + credit - reservedPacksForProduct(productId));
    }

    function stockErrorForDraft(values = draft) {
        const productId = values.factory_product_id;
        const packs = Number(values.quantity);

        if (!productId || !Number.isFinite(packs) || packs <= 0) {
            return null;
        }

        const available = availablePacksForProduct(productId);

        if (packs > available + 0.0001) {
            return (labels.packStockExceeded ?? v.quantityExceedsStock)
                .replace('{stock}', formatQuantityOrDash(available, locale))
                .replace('{available}', formatQuantityOrDash(available, locale));
        }

        return null;
    }

    function validateDraft() {
        const parsed = schema.safeParse({
            permanent_employee_id: form.data.permanent_employee_id || '1',
            type: 'product',
            advance_date: form.data.advance_date || '2020-01-01',
            ...draft,
        });

        if (!parsed.success) {
            const map = zodErrorToFieldMap(parsed.error);
            const next = {};
            for (const key of [
                'factory_product_id',
                'quantity_mode',
                'quantity',
                'total_weight',
                'weight_price',
            ]) {
                if (map[key]) {
                    next[key] = map[key];
                }
            }
            setDraftErrors(next);

            return false;
        }

        const stockError = stockErrorForDraft(draft);

        if (stockError) {
            setDraftErrors({ quantity: stockError });

            return false;
        }

        setDraftErrors({});

        return true;
    }

    function addDraftItem() {
        if (!validateDraft()) {
            return;
        }

        setItems((current) => [
            ...current,
            {
                ...draft,
                key: `${Date.now()}-${current.length}`,
            },
        ]);
        setDraft(emptyProductDraft());
        setDraftErrors({});
        form.clearErrors('items');
    }

    function removeItem(key) {
        setItems((current) => current.filter((item) => item.key !== key));
    }

    function resolveProductItems() {
        if (items.length > 0) {
            return items;
        }

        if (!validateDraft()) {
            return null;
        }

        const next = [{ ...draft, key: `draft-${Date.now()}` }];
        setItems(next);

        return next;
    }

    function validateClient() {
        if (isCreate && isProduct) {
            const productItems = resolveProductItems();

            if (!productItems || productItems.length === 0) {
                form.setError('items', labels.itemsRequired ?? v.required);

                return null;
            }

            const demandByProduct = productItems.reduce((map, item) => {
                const id = String(item.factory_product_id);
                const packs = Number(item.quantity) || 0;
                map[id] = (map[id] || 0) + packs;

                return map;
            }, {});

            for (const [productId, packs] of Object.entries(demandByProduct)) {
                const product = products.find((entry) => String(entry.id) === String(productId));
                const onHand = Number(product?.stock_on_hand);
                const available = Number.isFinite(onHand) ? onHand : 0;

                if (packs > available + 0.0001) {
                    form.setError(
                        'items',
                        (labels.packStockExceeded ?? v.quantityExceedsStock)
                            .replace('{stock}', formatQuantityOrDash(available, locale))
                            .replace('{available}', formatQuantityOrDash(available, locale)),
                    );

                    return null;
                }
            }

            const parsed = schema.safeParse({
                permanent_employee_id: form.data.permanent_employee_id,
                type: 'cash',
                advance_date: form.data.advance_date,
                amount: '1',
                notes: form.data.notes,
            });

            if (!parsed.success) {
                const map = zodErrorToFieldMap(parsed.error);
                delete map.amount;
                form.setError(map);

                return null;
            }

            form.clearErrors();

            return productItems;
        }

        const parsed = schema.safeParse(form.data);

        if (!parsed.success) {
            form.setError(zodErrorToFieldMap(parsed.error));

            return null;
        }

        if (isProduct) {
            const available = availablePacksForProduct(form.data.factory_product_id);
            const packs = Number(form.data.quantity);

            if (Number.isFinite(packs) && packs > available + 0.0001) {
                form.setError(
                    'quantity',
                    (labels.packStockExceeded ?? v.quantityExceedsStock)
                        .replace('{stock}', formatQuantityOrDash(available, locale))
                        .replace('{available}', formatQuantityOrDash(available, locale)),
                );

                return null;
            }
        }

        form.clearErrors();

        return [];
    }

    function submit() {
        const productItems = validateClient();

        if (productItems === null) {
            setConfirmOpen(false);

            return;
        }

        const options = {
            preserveScroll: true,
            onSuccess: () => setConfirmOpen(false),
            onError: () => setConfirmOpen(false),
        };

        if (isCreate && isProduct) {
            form.transform(() => ({
                permanent_employee_id: form.data.permanent_employee_id,
                type: 'product',
                advance_date: form.data.advance_date,
                notes: form.data.notes,
                items: productItems.map((item) => ({
                    factory_product_id: item.factory_product_id,
                    quantity_mode: item.quantity_mode,
                    quantity: item.quantity,
                    total_weight: item.total_weight,
                    weight_price: item.weight_price,
                })),
            }));
        } else {
            form.transform((data) => {
                const {
                    items: _items,
                    factory_product_id,
                    quantity_mode,
                    quantity,
                    total_weight,
                    weight_price,
                    ...rest
                } = data;

                if (rest.type === 'cash') {
                    return {
                        permanent_employee_id: rest.permanent_employee_id,
                        type: 'cash',
                        advance_date: rest.advance_date,
                        amount: rest.amount,
                        notes: rest.notes,
                    };
                }

                return {
                    ...rest,
                    factory_product_id,
                    quantity_mode,
                    quantity,
                    total_weight,
                    weight_price,
                };
            });
        }

        if (submitMethod === 'put') {
            form.put(submitUrl, options);
        } else {
            form.post(submitUrl, options);
        }
    }

    function renderProductFields({
        values,
        errors,
        onChange,
        idPrefix = '',
    }) {
        const isPack = values.quantity_mode !== 'weight';

        return (
            <div className="space-y-4">
                <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2 sm:col-span-2">
                        <Label htmlFor={`${idPrefix}factory_product_id`}>{labels.product}</Label>
                        {products.length === 0 ? (
                            <p className="text-muted-foreground text-sm">{labels.noProductsHint}</p>
                        ) : (
                            <ProductSearchSelect
                                id={`${idPrefix}factory_product_id`}
                                value={values.factory_product_id}
                                onValueChange={(value) => onChange('factory_product_id', value)}
                                products={products}
                                formatLabel={formatProductLabel}
                                placeholder={labels.selectProduct}
                                searchPlaceholder={labels.productSearchPlaceholder}
                                emptyLabel={labels.productSearchEmpty}
                                error={errors.factory_product_id}
                            />
                        )}
                        {selectedProduct ? (
                            <p className="text-muted-foreground text-xs tabular-nums">
                                {labels.colStock}:{' '}
                                {formatQuantityOrDash(selectedProduct.stock_on_hand, locale)}
                                {selectedProduct.unit_name ? ` ${selectedProduct.unit_name}` : ''}
                            </p>
                        ) : null}
                        {errors.factory_product_id ? (
                            <p className="text-destructive text-sm">{errors.factory_product_id}</p>
                        ) : null}
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor={`${idPrefix}quantity_mode`}>{labels.quantityBy}</Label>
                        <Select
                            value={values.quantity_mode || 'pack'}
                            onValueChange={(value) => onChange('quantity_mode', value)}
                        >
                            <SelectTrigger
                                id={`${idPrefix}quantity_mode`}
                                className={cn(errors.quantity_mode && 'border-destructive')}
                            >
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="pack">{labels.byPack}</SelectItem>
                                <SelectItem value="weight">{labels.byKg}</SelectItem>
                            </SelectContent>
                        </Select>
                        {errors.quantity_mode ? (
                            <p className="text-destructive text-sm">{errors.quantity_mode}</p>
                        ) : null}
                    </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    {isPack ? (
                        <>
                            <div className="space-y-2">
                                <Label htmlFor={`${idPrefix}quantity`}>{labels.packQuantity}</Label>
                                <Input
                                    id={`${idPrefix}quantity`}
                                    inputMode="decimal"
                                    value={values.quantity}
                                    onChange={(e) => onChange('quantity', e.target.value)}
                                    aria-invalid={Boolean(errors.quantity)}
                                    className={cn(errors.quantity && 'border-destructive')}
                                />
                                {errors.quantity ? (
                                    <p className="text-destructive text-sm">{errors.quantity}</p>
                                ) : null}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor={`${idPrefix}total_weight`}>{labels.totalWeight}</Label>
                                <Input
                                    id={`${idPrefix}total_weight`}
                                    inputMode="decimal"
                                    value={values.total_weight}
                                    onChange={(e) => onChange('total_weight', e.target.value)}
                                    aria-invalid={Boolean(errors.total_weight)}
                                    className={cn(errors.total_weight && 'border-destructive')}
                                />
                                {errors.total_weight ? (
                                    <p className="text-destructive text-sm">{errors.total_weight}</p>
                                ) : null}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor={`${idPrefix}weight_price`}>{labels.pricePerPack}</Label>
                                <Input
                                    id={`${idPrefix}weight_price`}
                                    inputMode="decimal"
                                    value={values.weight_price}
                                    onChange={(e) => onChange('weight_price', e.target.value)}
                                    aria-invalid={Boolean(errors.weight_price)}
                                    className={cn(errors.weight_price && 'border-destructive')}
                                />
                                {errors.weight_price ? (
                                    <p className="text-destructive text-sm">{errors.weight_price}</p>
                                ) : null}
                            </div>
                        </>
                    ) : (
                        <>
                            <div className="space-y-2">
                                <Label htmlFor={`${idPrefix}total_weight`}>{labels.totalWeight}</Label>
                                <Input
                                    id={`${idPrefix}total_weight`}
                                    inputMode="decimal"
                                    value={values.total_weight}
                                    onChange={(e) => onChange('total_weight', e.target.value)}
                                    aria-invalid={Boolean(errors.total_weight)}
                                    className={cn(errors.total_weight && 'border-destructive')}
                                />
                                {errors.total_weight ? (
                                    <p className="text-destructive text-sm">{errors.total_weight}</p>
                                ) : null}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor={`${idPrefix}quantity`}>{labels.totalPack}</Label>
                                <Input
                                    id={`${idPrefix}quantity`}
                                    inputMode="decimal"
                                    value={values.quantity}
                                    onChange={(e) => onChange('quantity', e.target.value)}
                                    aria-invalid={Boolean(errors.quantity)}
                                    className={cn(errors.quantity && 'border-destructive')}
                                />
                                {errors.quantity ? (
                                    <p className="text-destructive text-sm">{errors.quantity}</p>
                                ) : null}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor={`${idPrefix}weight_price`}>{labels.pricePerKg}</Label>
                                <Input
                                    id={`${idPrefix}weight_price`}
                                    inputMode="decimal"
                                    value={values.weight_price}
                                    onChange={(e) => onChange('weight_price', e.target.value)}
                                    aria-invalid={Boolean(errors.weight_price)}
                                    className={cn(errors.weight_price && 'border-destructive')}
                                />
                                {errors.weight_price ? (
                                    <p className="text-destructive text-sm">{errors.weight_price}</p>
                                ) : null}
                            </div>
                        </>
                    )}

                    <div className="space-y-2">
                        <Label>{labels.lineTotal}</Label>
                        <div className="flex h-9 items-center rounded-md border bg-muted/30 px-3 text-sm font-medium tabular-nums">
                            {formatMoneyAmountOrDash(advanceProductLineTotal(values), locale)}
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <>
            <ConfirmActionDialog
                open={confirmOpen}
                onOpenChange={setConfirmOpen}
                title={confirmTitle}
                description={confirmBody}
                confirmLabel={submitLabel}
                cancelLabel={cancelLabel}
                onConfirm={submit}
                processing={form.processing}
            />

            <form
                noValidate
                onSubmit={(e) => {
                    e.preventDefault();
                    if (validateClient() !== null) {
                        setConfirmOpen(true);
                    }
                }}
                className="mx-auto flex w-full max-w-4xl flex-col gap-6"
            >
                <Card>
                    <CardHeader>
                        <CardTitle>{labels.sectionAdvance}</CardTitle>
                        <CardDescription>{labels.sectionAdvanceHint}</CardDescription>
                    </CardHeader>

                    <CardContent className="space-y-8">
                        <section className="space-y-4">
                            <div>
                                <h3 className="text-sm font-semibold">{labels.sectionStaff}</h3>
                                <p className="text-muted-foreground text-sm">
                                    {labels.sectionStaffHint}
                                </p>
                            </div>

                            <div className="grid gap-4 sm:grid-cols-2">
                                <div className="space-y-2 sm:col-span-2">
                                    <Label htmlFor="permanent_employee_id">{labels.staffMember}</Label>
                                    {mode === 'edit' && selectedEmployee ? (
                                        <div className="rounded-md border bg-muted/30 px-3 py-2.5">
                                            <p className="font-medium">{selectedEmployee.full_name}</p>
                                            {selectedEmployee.designation_name ? (
                                                <p className="text-muted-foreground text-sm">
                                                    {selectedEmployee.designation_name}
                                                </p>
                                            ) : null}
                                        </div>
                                    ) : (
                                        <Select
                                            value={form.data.permanent_employee_id}
                                            onValueChange={(value) =>
                                                form.setData('permanent_employee_id', value)
                                            }
                                        >
                                            <SelectTrigger
                                                id="permanent_employee_id"
                                                className={cn(
                                                    form.errors.permanent_employee_id &&
                                                        'border-destructive',
                                                )}
                                            >
                                                <SelectValue placeholder={labels.selectStaff} />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {employees.map((employee) => (
                                                    <SelectItem
                                                        key={employee.id}
                                                        value={String(employee.id)}
                                                    >
                                                        {employee.full_name}
                                                        {employee.designation_name
                                                            ? ` — ${employee.designation_name}`
                                                            : ''}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    )}
                                    {form.errors.permanent_employee_id ? (
                                        <p className="text-destructive text-sm">
                                            {form.errors.permanent_employee_id}
                                        </p>
                                    ) : null}
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="advance_date">{labels.advanceDate}</Label>
                                    <AppDateInput
                                        id="advance_date"
                                        value={form.data.advance_date}
                                        onChange={(value) => form.setData('advance_date', value)}
                                        aria-invalid={Boolean(form.errors.advance_date)}
                                        className={cn(
                                            form.errors.advance_date && 'border-destructive',
                                        )}
                                    />
                                    {form.data.advance_date ? (
                                        <p className="text-muted-foreground text-xs">
                                            {formatEmployeeJoiningDateOrDash(form.data.advance_date)}
                                        </p>
                                    ) : null}
                                    {form.errors.advance_date ? (
                                        <p className="text-destructive text-sm">
                                            {form.errors.advance_date}
                                        </p>
                                    ) : null}
                                </div>
                            </div>
                        </section>

                        <section className="space-y-4 border-t pt-8">
                            <div>
                                <h3 className="text-sm font-semibold">{labels.advanceType}</h3>
                            </div>

                            <div className="grid grid-cols-2 gap-2 rounded-lg border border-border p-1">
                                <Button
                                    type="button"
                                    variant={form.data.type === 'cash' ? 'default' : 'ghost'}
                                    className="h-10 gap-2"
                                    onClick={() => setAdvanceType('cash')}
                                >
                                    <Banknote className="size-4 shrink-0" />
                                    {labels.typeCash}
                                </Button>
                                <Button
                                    type="button"
                                    variant={form.data.type === 'product' ? 'default' : 'ghost'}
                                    className="h-10 gap-2"
                                    onClick={() => setAdvanceType('product')}
                                >
                                    <Package className="size-4 shrink-0" />
                                    {labels.typeProduct}
                                </Button>
                            </div>
                            {form.errors.type ? (
                                <p className="text-destructive text-sm">{form.errors.type}</p>
                            ) : null}
                        </section>

                        <section className="space-y-4 border-t pt-8">
                            <div>
                                <h3 className="text-sm font-semibold">{labels.sectionAmount}</h3>
                                <p className="text-muted-foreground text-sm">
                                    {isProduct
                                        ? labels.sectionAmountProductHint
                                        : labels.sectionAmountCashHint}
                                </p>
                            </div>

                            {isProduct ? (
                                <div className="space-y-4 rounded-xl border border-border bg-muted/20 p-4">
                                    {isCreate ? (
                                        <>
                                            {renderProductFields({
                                                values: draft,
                                                errors: draftErrors,
                                                onChange: updateDraft,
                                                idPrefix: 'draft-',
                                            })}
                                            <div className="flex justify-end">
                                                <Button type="button" variant="secondary" onClick={addDraftItem}>
                                                    <Plus className="size-4" />
                                                    {labels.addItem}
                                                </Button>
                                            </div>

                                            <div className="overflow-x-auto rounded-md border bg-background">
                                                <Table>
                                                    <TableHeader>
                                                        <TableRow>
                                                            <TableHead>{labels.product}</TableHead>
                                                            <TableHead>{labels.quantityBy}</TableHead>
                                                            <TableHead className="text-end">
                                                                {labels.packQuantity}
                                                            </TableHead>
                                                            <TableHead className="text-end">
                                                                {labels.totalWeight}
                                                            </TableHead>
                                                            <TableHead className="text-end">
                                                                {labels.lineTotal}
                                                            </TableHead>
                                                            <TableHead className="w-[1%]" />
                                                        </TableRow>
                                                    </TableHeader>
                                                    <TableBody>
                                                        {items.length === 0 ? (
                                                            <TableRow>
                                                                <TableCell
                                                                    colSpan={6}
                                                                    className="text-muted-foreground h-16 text-center text-sm"
                                                                >
                                                                    {labels.itemsEmpty}
                                                                </TableCell>
                                                            </TableRow>
                                                        ) : (
                                                            items.map((item) => (
                                                                <TableRow key={item.key}>
                                                                    <TableCell>
                                                                        {productName(item.factory_product_id)}
                                                                    </TableCell>
                                                                    <TableCell>
                                                                        {item.quantity_mode === 'pack'
                                                                            ? labels.byPack
                                                                            : labels.byKg}
                                                                    </TableCell>
                                                                    <TableCell className="text-end tabular-nums">
                                                                        {item.quantity}
                                                                    </TableCell>
                                                                    <TableCell className="text-end tabular-nums">
                                                                        {item.total_weight}
                                                                    </TableCell>
                                                                    <TableCell className="text-end font-medium tabular-nums">
                                                                        {formatMoneyAmountOrDash(
                                                                            advanceProductLineTotal(item),
                                                                            locale,
                                                                        )}
                                                                    </TableCell>
                                                                    <TableCell>
                                                                        <Button
                                                                            type="button"
                                                                            variant="ghost"
                                                                            size="icon"
                                                                            onClick={() => removeItem(item.key)}
                                                                            aria-label={labels.removeItem}
                                                                        >
                                                                            <Trash2 className="size-4" />
                                                                        </Button>
                                                                    </TableCell>
                                                                </TableRow>
                                                            ))
                                                        )}
                                                    </TableBody>
                                                </Table>
                                            </div>
                                            {form.errors.items ? (
                                                <p className="text-destructive text-sm">{form.errors.items}</p>
                                            ) : null}
                                        </>
                                    ) : (
                                        renderProductFields({
                                            values: form.data,
                                            errors: form.errors,
                                            onChange: (field, value) => form.setData(field, value),
                                        })
                                    )}
                                </div>
                            ) : (
                                <div className="max-w-sm space-y-2">
                                    <Label htmlFor="advance_amount">{labels.cashAmount}</Label>
                                    <Input
                                        id="advance_amount"
                                        inputMode="decimal"
                                        value={form.data.amount}
                                        onChange={(e) => form.setData('amount', e.target.value)}
                                        aria-invalid={Boolean(form.errors.amount)}
                                        className={cn(form.errors.amount && 'border-destructive')}
                                    />
                                    {form.errors.amount ? (
                                        <p className="text-destructive text-sm">{form.errors.amount}</p>
                                    ) : null}
                                </div>
                            )}

                            <div className="flex items-center justify-between gap-4 rounded-lg border bg-muted/30 px-4 py-3">
                                <span className="text-muted-foreground text-sm">
                                    {isProduct ? labels.productTotal : labels.cashAmount}
                                </span>
                                <span className="text-lg font-semibold tabular-nums">
                                    {formatMoneyAmountOrDash(displayAmount, locale)}
                                </span>
                            </div>
                        </section>

                        <section className="space-y-4 border-t pt-8">
                            <div>
                                <h3 className="text-sm font-semibold">{labels.sectionNotes}</h3>
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="advance_notes" className="sr-only">
                                    {labels.notes}
                                </Label>
                                <Textarea
                                    id="advance_notes"
                                    value={form.data.notes}
                                    onChange={(e) => form.setData('notes', e.target.value)}
                                    rows={3}
                                    placeholder={labels.notesPlaceholder}
                                />
                                {form.errors.notes ? (
                                    <p className="text-destructive text-sm">{form.errors.notes}</p>
                                ) : null}
                            </div>
                        </section>
                    </CardContent>

                    <CardFooter className="flex justify-end border-t bg-muted/20">
                        <Button type="submit" disabled={form.processing}>
                            {form.processing ? (
                                <>
                                    <Spinner className="size-4" />
                                    {submittingLabel}
                                </>
                            ) : (
                                <>
                                    <Save className="size-4" />
                                    {submitLabel}
                                </>
                            )}
                        </Button>
                    </CardFooter>
                </Card>
            </form>
        </>
    );
}
