import { useForm } from '@inertiajs/react';
import { Plus, Save, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import { create as purchaseProductsCreate } from '@/actions/App/Http/Controllers/PurchaseProductController';
import { PurchaseSupplierSelect } from '@/components/purchases/purchase-supplier-select';
import { SupplierPaymentFields } from '@/components/purchases/supplier-payment-fields';
import { StorageFilePreview } from '@/components/employees/storage-file-preview';
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,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useLanguage } from '@/contexts/language-context';
import { formatPurchaseMoneyOrDash } from '@/lib/dates';
import {
    formatBaseQuantity,
    productFactorForId,
    productUsesBaseUnit,
    purchaseLineTotalInBase,
} from '@/lib/purchase-quantity';
import { isImageFileUrl } from '@/lib/storage-files';
import { cn } from '@/lib/utils';
import { buildSupplierPaymentApiFields } from '@/lib/supplier-payment-payload';
import {
    buildStorePurchaseSchema,
    buildUpdatePurchaseSchema,
} from '@/validation/schemas';
import { Link } from '@inertiajs/react';

function todayYmd() {
    const now = new Date();
    const y = now.getFullYear();
    const m = String(now.getMonth() + 1).padStart(2, '0');
    const d = String(now.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
}

function emptyItem() {
    return {
        purchase_product_id: '',
        quantity: '',
        unit_price: '',
    };
}

function zodErrorToNestedFieldMap(error) {
    /** @type {Record<string, string>} */
    const out = {};

    for (const issue of error.issues) {
        const key = issue.path.join('.');
        if (key && !out[key]) {
            out[key] = issue.message;
        }
    }

    return out;
}

function BillFileField({ id, label, hint, accept, error, currentUrl, currentLabel, onChange }) {
    const [pickedPreview, setPickedPreview] = useState(null);

    useEffect(() => {
        return () => {
            if (pickedPreview?.startsWith('blob:')) {
                URL.revokeObjectURL(pickedPreview);
            }
        };
    }, [pickedPreview]);

    function handleChange(e) {
        const file = e.target.files?.[0] ?? null;

        setPickedPreview((prev) => {
            if (prev?.startsWith('blob:')) {
                URL.revokeObjectURL(prev);
            }
            if (file?.type.startsWith('image/')) {
                return URL.createObjectURL(file);
            }
            return null;
        });

        onChange(e);
    }

    const previewUrl =
        pickedPreview ?? (currentUrl && isImageFileUrl(currentUrl) ? currentUrl : null);

    return (
        <div className="space-y-2">
            <Label htmlFor={id}>{label}</Label>
            {previewUrl ? (
                <StorageFilePreview
                    url={previewUrl}
                    alt={label}
                    linkLabel={currentLabel}
                    size="md"
                />
            ) : currentUrl ? (
                <StorageFilePreview
                    url={currentUrl}
                    alt={label}
                    linkLabel={currentLabel}
                    size="md"
                />
            ) : null}
            <Input
                id={id}
                name={id}
                type="file"
                accept={accept}
                className="cursor-pointer text-sm file:me-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-sm file:font-medium"
                onChange={handleChange}
            />
            {hint ? <p className="text-muted-foreground text-xs">{hint}</p> : null}
            {error ? <p className="text-destructive text-sm">{error}</p> : null}
        </div>
    );
}

function lineTotal(quantity, unitPrice) {
    const qty = Number(quantity);
    const price = Number(unitPrice);

    if (!Number.isFinite(qty) || !Number.isFinite(price)) {
        return null;
    }

    return Math.round(qty * price * 100) / 100;
}

/**
 * @param {object} props
 * @param {object} props.item
 * @param {number} props.index
 * @param {Record<string, string>} props.labels
 * @param {Array<{id: number, name: string, unit_name?: string|null, base_unit_name?: string|null, factor_to_base?: string|number, uses_base_unit?: boolean, is_active?: boolean}>} props.products
 * @param {'en'|'fa'} props.locale
 * @param {string} props.currency
 * @param {Record<string, string>} props.errors
 * @param {boolean} props.canRemove
 * @param {'cards'|'table'} props.variant
 * @param {(index: number, field: string, value: string) => void} props.onUpdate
 * @param {(index: number) => void} props.onRemove
 */
function PurchaseItemLine({
    item,
    index,
    labels,
    products,
    locale,
    currency,
    errors,
    canRemove,
    variant,
    onUpdate,
    onRemove,
}) {
    const rowLineTotal = lineTotal(item.quantity, item.unit_price);
    const rowTotalDisplay = formatPurchaseMoneyOrDash(rowLineTotal, currency, locale);
    const selectedProduct =
        item.purchase_product_id !== ''
            ? products.find((row) => String(row.id) === String(item.purchase_product_id))
            : null;
    const usesBaseUnit = productUsesBaseUnit(selectedProduct ?? {});
    const factorToBase = productFactorForId(products, item.purchase_product_id);
    const totalInBase =
        usesBaseUnit && item.purchase_product_id !== ''
            ? purchaseLineTotalInBase(item.quantity, factorToBase)
            : null;
    const totalInBaseDisplay = formatBaseQuantity(totalInBase, locale);
    const baseUnitName = selectedProduct?.base_unit_name ?? labels.totalInBase;
    const productError = errors[`items.${index}.purchase_product_id`];
    const quantityError = errors[`items.${index}.quantity`];
    const unitPriceError = errors[`items.${index}.unit_price`];

    const productSelect = (
        <div className="space-y-1">
            <Select
                value={
                    item.purchase_product_id !== ''
                        ? String(item.purchase_product_id)
                        : ''
                }
                onValueChange={(value) => onUpdate(index, 'purchase_product_id', value)}
            >
                <SelectTrigger
                    id={`purchase-item-product-${index}`}
                    aria-invalid={Boolean(productError)}
                    className={cn(productError && 'border-destructive', variant === 'table' && 'h-9')}
                >
                    <SelectValue placeholder={labels.productPlaceholder} />
                </SelectTrigger>
                <SelectContent>
                    {products.map((product) => (
                        <SelectItem key={product.id} value={String(product.id)}>
                            {product.name}
                            {product.unit_name ? ` (${product.unit_name})` : ''}
                            {product.is_active === false ? ` (${labels.productInactive})` : ''}
                        </SelectItem>
                    ))}
                </SelectContent>
            </Select>
            {productError ? (
                <p className="text-destructive text-xs">{productError}</p>
            ) : null}
        </div>
    );

    const quantityInput = (
        <div className="space-y-1">
            <Input
                id={`purchase-item-qty-${index}`}
                type="number"
                min="0"
                step="0.001"
                value={item.quantity}
                onChange={(e) => onUpdate(index, 'quantity', e.target.value)}
                placeholder={labels.quantityPlaceholder}
                aria-invalid={Boolean(quantityError)}
                className={cn(quantityError && 'border-destructive', variant === 'table' && 'h-9')}
            />
            {totalInBase !== null ? (
                <p className="text-muted-foreground text-xs tabular-nums">
                    {labels.totalInBaseLine
                        .replace('{qty}', totalInBaseDisplay)
                        .replace('{unit}', baseUnitName)}
                </p>
            ) : null}
            {quantityError ? (
                <p className="text-destructive text-xs">{quantityError}</p>
            ) : null}
        </div>
    );

    const totalInBaseCell = (
        <div className="border-input bg-background flex h-9 items-center rounded-md border px-3 text-sm tabular-nums">
            {totalInBase !== null ? (
                <span>
                    {labels.totalInBaseValue
                        .replace('{qty}', totalInBaseDisplay)
                        .replace('{unit}', baseUnitName)}
                </span>
            ) : (
                <span className="text-muted-foreground">—</span>
            )}
        </div>
    );

    const unitPriceInput = (
        <div className="space-y-1">
            <Input
                id={`purchase-item-price-${index}`}
                type="number"
                min="0"
                step="0.01"
                value={item.unit_price}
                onChange={(e) => onUpdate(index, 'unit_price', e.target.value)}
                placeholder={labels.unitPricePlaceholder}
                aria-invalid={Boolean(unitPriceError)}
                className={cn(unitPriceError && 'border-destructive', variant === 'table' && 'h-9')}
            />
            {unitPriceError ? (
                <p className="text-destructive text-xs">{unitPriceError}</p>
            ) : null}
        </div>
    );

    const lineTotalCell = (
        <div className="border-input bg-background flex h-9 items-center rounded-md border px-3 text-sm font-medium tabular-nums">
            {rowTotalDisplay}
        </div>
    );

    const removeButton = (
        <Button
            type="button"
            variant="outline"
            size="icon"
            className="size-9 shrink-0"
            disabled={!canRemove}
            onClick={() => onRemove(index)}
            aria-label={labels.removeProductLine}
        >
            <Trash2 className="size-4" />
        </Button>
    );

    if (variant === 'table') {
        return (
            <TableRow>
                <TableCell className="text-muted-foreground tabular-nums align-top">
                    {index + 1}
                </TableCell>
                <TableCell className="min-w-[12rem] align-top">{productSelect}</TableCell>
                <TableCell className="align-top">{quantityInput}</TableCell>
                <TableCell className="align-top">{totalInBaseCell}</TableCell>
                <TableCell className="align-top">{unitPriceInput}</TableCell>
                <TableCell className="align-top">{lineTotalCell}</TableCell>
                <TableCell className="align-top">{removeButton}</TableCell>
            </TableRow>
        );
    }

    return (
        <div className="grid gap-4 rounded-lg border border-border/80 bg-muted/20 p-4 sm:grid-cols-12">
            <div className="space-y-2 sm:col-span-4">
                <Label htmlFor={`purchase-item-product-${index}`}>{labels.product}</Label>
                {productSelect}
            </div>
            <div className="space-y-2 sm:col-span-2">
                <Label htmlFor={`purchase-item-qty-${index}`}>{labels.quantity}</Label>
                {quantityInput}
            </div>
            <div className="space-y-2 sm:col-span-2">
                <Label htmlFor={`purchase-item-price-${index}`}>{labels.unitPrice}</Label>
                {unitPriceInput}
            </div>
            <div className="space-y-2 sm:col-span-3">
                <Label>{labels.lineTotal}</Label>
                {lineTotalCell}
            </div>
            <div className="flex items-end sm:col-span-1">{removeButton}</div>
        </div>
    );
}

/**
 * @param {object} props
 * @param {'create'|'edit'} props.mode
 * @param {Record<string, string>} props.labels
 * @param {Record<string, string>} props.validation
 * @param {Record<string, string>} props.appActions
 * @param {Array<{id: number, name: string, unit_name?: string|null, is_active?: boolean}>} props.products
 * @param {Array<{id: number, name: string, is_active?: boolean}>} props.suppliers
 * @param {object} [props.initial]
 * @param {string} props.submitUrl
 * @param {'post'|'put'} props.submitMethod
 * @param {Array<string>} [props.currencies]
 * @param {Array<string>} [props.paymentMethods]
 * @param {boolean} [props.canRecordPayment]
 * @param {number} [props.dueAmount]
 */
export function PurchaseForm({
    mode,
    labels,
    validation,
    appActions,
    products,
    suppliers = [],
    initial,
    submitUrl,
    submitMethod,
    currencies = ['afn', 'usd'],
    paymentMethods = ['cash', 'bank', 'other'],
    canRecordPayment = false,
    dueAmount = 0,
}) {
    const { locale } = useLanguage();
    const initialItems =
        initial?.items?.length > 0
            ? initial.items.map((item) => ({
                  purchase_product_id: item.purchase_product_id ?? '',
                  quantity: item.quantity ?? '',
                  unit_price: item.unit_price ?? '',
              }))
            : [emptyItem()];

    const form = useForm({
        bill_number: initial?.bill_number ?? '',
        currency: initial?.currency ?? 'afn',
        purchased_at: initial?.purchased_at ?? todayYmd(),
        supplier_id: initial?.supplier_id ?? '',
        notes: initial?.notes ?? '',
        bill_file: null,
        items: initialItems,
        payment: {
            enabled: false,
            currency: initial?.currency ?? 'afn',
            amount: '',
            paid_at: todayYmd(),
            payment_method: 'cash',
            reference: '',
            notes: '',
            exchange_rate: '',
        },
    });
    const [confirmOpen, setConfirmOpen] = useState(false);

    const schema = useMemo(
        () =>
            mode === 'create'
                ? buildStorePurchaseSchema(validation)
                : buildUpdatePurchaseSchema(validation),
        [mode, validation],
    );

    const grandTotal = useMemo(() => {
        return form.data.items.reduce((sum, item) => {
            const total = lineTotal(item.quantity, item.unit_price);
            return sum + (total ?? 0);
        }, 0);
    }, [form.data.items]);

    const grandTotalDisplay = formatPurchaseMoneyOrDash(
        grandTotal,
        form.data.currency,
        locale,
    );

    const updateItem = useCallback(
        (index, field, value) => {
            const next = form.data.items.map((item, i) =>
                i === index ? { ...item, [field]: value } : item,
            );
            form.setData('items', next);
        },
        [form],
    );

    const addItem = useCallback(() => {
        form.setData('items', [...form.data.items, emptyItem()]);
    }, [form]);

    const removeItem = useCallback(
        (index) => {
            if (form.data.items.length <= 1) {
                return;
            }
            form.setData(
                'items',
                form.data.items.filter((_, i) => i !== index),
            );
        },
        [form],
    );

    function handleSubmit(e) {
        e.preventDefault();
        form.clearErrors();
        const parsed = schema.safeParse(form.data);
        if (!parsed.success) {
            form.setError(zodErrorToNestedFieldMap(parsed.error));
            return;
        }
        setConfirmOpen(true);
    }

    function commitSave() {
        form.clearErrors();
        const parsed = schema.safeParse(form.data);
        if (!parsed.success) {
            form.setError(zodErrorToNestedFieldMap(parsed.error));
            setConfirmOpen(false);
            return;
        }

        form.transform((data) => {
            const supplierId =
                data.supplier_id === '' || data.supplier_id === 'none'
                    ? null
                    : Number(data.supplier_id);

            const payment =
                canRecordPayment && data.payment?.enabled
                    ? {
                          enabled: true,
                          ...buildSupplierPaymentApiFields(
                              data.payment,
                              data.currency,
                          ),
                      }
                    : undefined;

            return {
                ...data,
                supplier_id: supplierId,
                payment,
            };
        });

        const options = {
            forceFormData: true,
            onError: () => toast.error(appActions.requestFailed),
        };

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

        form.post(submitUrl, options);
    }

    const isCreate = mode === 'create';
    const itemsError = form.errors.items;
    const hasProducts = products.length > 0;
    const useItemsTable = form.data.items.length > 2;
    const docAccept =
        'image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp,application/pdf,.pdf';

    const hasSupplier =
        form.data.supplier_id !== '' && form.data.supplier_id !== 'none';
    const showPaymentSection =
        canRecordPayment && hasSupplier && (isCreate || dueAmount > 0.001);

    function setPaymentField(field, value) {
        form.setData((data) => ({
            ...data,
            payment: {
                ...data.payment,
                [field]: value,
            },
        }));
    }

    function setPurchaseCurrency(value) {
        form.setData((data) => ({
            ...data,
            currency: value,
            payment: {
                ...data.payment,
                currency: value,
                exchange_rate: '',
            },
        }));
    }

    const maxBillPayment =
        isCreate ? grandTotal : Math.min(grandTotal, dueAmount);

    return (
        <>
            <ConfirmActionDialog
                open={confirmOpen}
                onOpenChange={setConfirmOpen}
                title={isCreate ? labels.confirmSaveTitle : labels.confirmUpdateTitle}
                description={isCreate ? labels.confirmSaveBody : labels.confirmUpdateBody}
                confirmLabel={isCreate ? labels.savePurchase : labels.updatePurchase}
                cancelLabel={appActions.cancel}
                processing={form.processing}
                onConfirm={commitSave}
            />

            <form
                onSubmit={handleSubmit}
                className="mx-auto flex w-full max-w-4xl flex-col gap-6"
            >
                <Card>
                    <CardHeader>
                        <CardTitle>
                            {isCreate ? labels.createHeadTitle : labels.editHeadTitle}
                        </CardTitle>
                        <CardDescription>
                            {isCreate ? labels.createDescription : labels.editDescription}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="grid gap-6 sm:grid-cols-2">
                            <div className="space-y-2">
                                <Label htmlFor="purchase-bill-number">{labels.billNumber}</Label>
                                <Input
                                    id="purchase-bill-number"
                                    value={form.data.bill_number}
                                    onChange={(e) => form.setData('bill_number', e.target.value)}
                                    placeholder={labels.billNumberPlaceholder}
                                    autoComplete="off"
                                    aria-invalid={Boolean(form.errors.bill_number)}
                                    className={cn(form.errors.bill_number && 'border-destructive')}
                                />
                                {form.errors.bill_number ? (
                                    <p className="text-destructive text-sm">
                                        {form.errors.bill_number}
                                    </p>
                                ) : null}
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="purchase-date">{labels.purchasedAt}</Label>
                                <AppDateInput
                                    id="purchase-date"
                                    value={form.data.purchased_at}
                                    onChange={(value) => form.setData('purchased_at', value)}
                                    invalid={Boolean(form.errors.purchased_at)}
                                />
                                {form.errors.purchased_at ? (
                                    <p className="text-destructive text-sm">
                                        {form.errors.purchased_at}
                                    </p>
                                ) : null}
                            </div>
                        </div>

                        <div className="grid gap-6 sm:grid-cols-2">
                            <div className="space-y-2">
                                <Label htmlFor="purchase-currency">{labels.currency}</Label>
                                <Select
                                    value={form.data.currency}
                                    onValueChange={setPurchaseCurrency}
                                >
                                    <SelectTrigger
                                        id="purchase-currency"
                                        aria-invalid={Boolean(form.errors.currency)}
                                        className={cn(form.errors.currency && 'border-destructive')}
                                    >
                                        <SelectValue placeholder={labels.currencyPlaceholder} />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="usd">{labels.currencyUsd}</SelectItem>
                                        <SelectItem value="afn">{labels.currencyAfn}</SelectItem>
                                    </SelectContent>
                                </Select>
                                {form.errors.currency ? (
                                    <p className="text-destructive text-sm">{form.errors.currency}</p>
                                ) : null}
                            </div>

                            <PurchaseSupplierSelect
                                suppliers={suppliers}
                                value={form.data.supplier_id}
                                onValueChange={(value) =>
                                    form.setData(
                                        'supplier_id',
                                        value === 'none' ? '' : value,
                                    )
                                }
                                labels={labels}
                                error={form.errors.supplier_id}
                            />
                        </div>

                        <BillFileField
                            id="bill_file"
                            label={labels.billFile}
                            hint={labels.billFileHint}
                            accept={docAccept}
                            error={form.errors.bill_file}
                            currentUrl={initial?.bill_file_url}
                            currentLabel={labels.viewCurrentBillFile}
                            onChange={(e) => {
                                form.setData('bill_file', e.target.files?.[0] ?? null);
                                if (form.errors.bill_file) {
                                    form.clearErrors('bill_file');
                                }
                            }}
                        />

                        <div className="space-y-4 rounded-xl border border-border p-4">
                            <div className="flex flex-wrap items-center justify-between gap-3">
                                <div>
                                    <h3 className="text-sm font-semibold">
                                        {labels.productsSection}
                                    </h3>
                                    <p className="text-muted-foreground text-sm">
                                        {labels.productsSectionHint}
                                    </p>
                                </div>
                                {hasProducts ? (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        onClick={addItem}
                                    >
                                        <Plus className="size-4" />
                                        {labels.addProductLine}
                                    </Button>
                                ) : null}
                            </div>

                            {!hasProducts ? (
                                <div className="space-y-2">
                                    <p className="text-muted-foreground text-sm">
                                        {labels.noProductsHint}
                                    </p>
                                    <Link
                                        href={purchaseProductsCreate.url()}
                                        className="text-primary text-sm font-medium underline-offset-4 hover:underline"
                                    >
                                        {labels.addProductLink}
                                    </Link>
                                </div>
                            ) : useItemsTable ? (
                                <div className="overflow-x-auto rounded-lg border border-border">
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead className="w-12">
                                                    {labels.colSerial}
                                                </TableHead>
                                                <TableHead className="min-w-[12rem]">
                                                    {labels.product}
                                                </TableHead>
                                                <TableHead className="w-28">
                                                    {labels.quantity}
                                                </TableHead>
                                                <TableHead className="w-28">
                                                    {labels.totalInBase}
                                                </TableHead>
                                                <TableHead className="w-32">
                                                    {labels.unitPrice}
                                                </TableHead>
                                                <TableHead className="w-32">
                                                    {labels.lineTotal}
                                                </TableHead>
                                                <TableHead className="w-14">
                                                    <span className="sr-only">
                                                        {labels.removeProductLine}
                                                    </span>
                                                </TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {form.data.items.map((item, index) => (
                                                <PurchaseItemLine
                                                    key={index}
                                                    item={item}
                                                    index={index}
                                                    labels={labels}
                                                    products={products}
                                                    locale={locale}
                                                    currency={form.data.currency}
                                                    errors={form.errors}
                                                    canRemove={form.data.items.length > 1}
                                                    variant="table"
                                                    onUpdate={updateItem}
                                                    onRemove={removeItem}
                                                />
                                            ))}
                                        </TableBody>
                                    </Table>
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    {form.data.items.map((item, index) => (
                                        <PurchaseItemLine
                                            key={index}
                                            item={item}
                                            index={index}
                                            labels={labels}
                                            products={products}
                                            locale={locale}
                                            currency={form.data.currency}
                                            errors={form.errors}
                                            canRemove={form.data.items.length > 1}
                                            variant="cards"
                                            onUpdate={updateItem}
                                            onRemove={removeItem}
                                        />
                                    ))}
                                </div>
                            )}

                            {itemsError ? (
                                <p className="text-destructive text-sm">{itemsError}</p>
                            ) : null}
                        </div>

                        <div className="grid gap-6 sm:grid-cols-2">
                            <div className="space-y-2 sm:col-span-1 sm:col-start-2">
                                <Label>{labels.totalAmount}</Label>
                                <div className="border-input bg-muted/40 flex h-10 items-center rounded-md border px-3 text-sm font-semibold tabular-nums">
                                    {grandTotalDisplay}
                                </div>
                            </div>
                        </div>

                        {showPaymentSection ? (
                            <div className="space-y-4 rounded-xl border border-border p-4">
                                <div className="flex items-start gap-3">
                                    <Checkbox
                                        id="purchase-payment-enabled"
                                        checked={form.data.payment.enabled}
                                        onCheckedChange={(checked) => {
                                            const enabled = checked === true;
                                            form.setData((data) => ({
                                                ...data,
                                                payment: {
                                                    ...data.payment,
                                                    enabled,
                                                    ...(enabled
                                                        ? {
                                                              currency: data.currency,
                                                              exchange_rate: '',
                                                          }
                                                        : {}),
                                                },
                                            }));
                                        }}
                                    />
                                    <div className="space-y-1">
                                        <Label
                                            htmlFor="purchase-payment-enabled"
                                            className="cursor-pointer"
                                        >
                                            {labels.paymentSection}
                                        </Label>
                                        <p className="text-muted-foreground text-sm">
                                            {labels.paymentSectionHint}
                                        </p>
                                    </div>
                                </div>

                                {form.data.payment.enabled ? (
                                    <>
                                    <p className="text-muted-foreground text-xs">
                                        {labels.overpayCreditHint}
                                    </p>
                                    <SupplierPaymentFields
                                        labels={labels}
                                        locale={locale}
                                        currencies={currencies}
                                        paymentMethods={paymentMethods}
                                        billCurrency={form.data.currency}
                                        maxBillAmount={maxBillPayment}
                                        data={form.data.payment}
                                        errors={{
                                            amount:
                                                form.errors['payment.amount'] ??
                                                form.errors.amount,
                                            paid_at:
                                                form.errors['payment.paid_at'] ??
                                                form.errors.paid_at,
                                            exchange_rate:
                                                form.errors['payment.exchange_rate'] ??
                                                form.errors.exchange_rate,
                                        }}
                                        onChange={setPaymentField}
                                        idPrefix="purchase-inline-payment"
                                        compact
                                    />
                                    </>
                                ) : null}
                            </div>
                        ) : null}

                        <div className="space-y-2">
                            <Label htmlFor="purchase-notes">{labels.notes}</Label>
                            <textarea
                                id="purchase-notes"
                                value={form.data.notes}
                                onChange={(e) => form.setData('notes', e.target.value)}
                                placeholder={labels.notesPlaceholder}
                                rows={3}
                                aria-invalid={Boolean(form.errors.notes)}
                                className={cn(
                                    'border-input placeholder:text-muted-foreground flex min-h-[5rem] w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none md:text-sm',
                                    'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
                                    form.errors.notes && 'border-destructive',
                                )}
                            />
                            {form.errors.notes ? (
                                <p className="text-destructive text-sm">{form.errors.notes}</p>
                            ) : null}
                        </div>

                        <div className="flex flex-wrap items-center gap-3 pt-2">
                            <Button type="submit" disabled={form.processing || !hasProducts}>
                                <Save className="size-4" />
                                {form.processing
                                    ? isCreate
                                        ? labels.savingPurchase
                                        : labels.updatingPurchase
                                    : isCreate
                                      ? labels.savePurchase
                                      : labels.updatePurchase}
                            </Button>
                        </div>
                    </CardContent>
                </Card>
            </form>
        </>
    );
}
