import { FileUploadInput } from '@admin/components/ui/forms/file-upload-input';
import { FormGroup } from '@admin/components/ui/forms/form-group';
import { FormNumberInput } from '@admin/components/ui/forms/form-number-input';
import { FormSelect } from '@admin/components/ui/forms/form-select';
import { FormSwitch } from '@admin/components/ui/forms/form-switch';

export type MenuCurrency = {
    code: string;
    name: string;
};

type ItemFormData = {
    menu_category_id: string;
    name: string;
    description: string;
    price: string;
    currency_code: string;
    image: string;
    sort_order: number;
    status: boolean;
};

type ItemFormFieldsProps = {
    data: ItemFormData;
    errors: Partial<Record<keyof ItemFormData, string>>;
    setData: (key: string, value: unknown) => void;
    categories: { id: number; name: string }[];
    currencies: MenuCurrency[];
    tzsPerUsd: string | null;
    imageInputId?: string;
    statusId?: string;
};

function mediaUrl(path: string): string {
    if (!path) {
        return '';
    }

    if (path.startsWith('/') || path.startsWith('http')) {
        return path;
    }

    return `/storage/${path}`;
}

function priceHelp(amount: string, currency: string, tzsPerUsd: string | null): string {
    if (currency === 'USD') {
        return 'The dining page shows this dollar amount.';
    }

    const rate = Number(tzsPerUsd);
    const value = Number(amount);

    if (currency === 'TZS' && rate && value) {
        const usd = value / rate;

        return `The dining page shows about USD ${usd.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} at the current rate.`;
    }

    return 'Enter the amount in the selected currency. The dining page shows the US dollar equivalent.';
}

export function ItemFormFields({
    data,
    errors,
    setData,
    categories,
    currencies,
    tzsPerUsd,
    imageInputId = 'menu-item-image',
    statusId = 'menu-item-status',
}: ItemFormFieldsProps) {
    return (
        <>
            <FormSelect
                label="Category"
                value={data.menu_category_id}
                options={categories.map((category) => ({ value: String(category.id), label: category.name }))}
                placeholder="Select a category"
                error={errors.menu_category_id}
                sortAlphabetically={false}
                onChange={(value) => setData('menu_category_id', value)}
            />

            <FormGroup
                label="Dish"
                error={errors.name}
                inputProps={{
                    value: data.name,
                    onChange: (event) => setData('name', event.target.value),
                    required: true,
                }}
            />

            <FormGroup
                as="textarea"
                label="Description"
                error={errors.description}
                inputProps={{
                    value: data.description,
                    rows: 3,
                    onChange: (event) => setData('description', event.target.value),
                }}
            />

            <FormSelect
                label="Currency"
                value={data.currency_code}
                options={currencies.map((currency) => ({ value: currency.code, label: `${currency.code} — ${currency.name}` }))}
                placeholder="Select a currency"
                error={errors.currency_code}
                sortAlphabetically={false}
                onChange={(value) => setData('currency_code', value)}
            />

            <FormGroup
                label="Price"
                helpText={priceHelp(data.price, data.currency_code, tzsPerUsd)}
                error={errors.price}
                inputProps={{
                    value: data.price,
                    inputMode: 'decimal',
                    onChange: (event) => setData('price', event.target.value),
                    required: true,
                }}
            />

            <FileUploadInput
                label="Photo (100×100 px recommended)"
                helpText="Square photo beside the dish name."
                inputId={imageInputId}
                uploadUrl="/admin/api/menu_item/upload_image"
                accept="image/jpeg,image/png,image/jpg,image/webp"
                previewUrl={mediaUrl(data.image)}
                previewType="image"
                error={errors.image}
                onSuccess={(filename) => setData('image', filename)}
            />

            <FormNumberInput
                label="Display order"
                helpText="Lower numbers appear first inside the category. The list splits into two columns."
                min={0}
                value={data.sort_order}
                error={errors.sort_order}
                required
                onChange={(value) => setData('sort_order', value)}
            />

            <FormSwitch
                id={statusId}
                label="Published"
                checked={data.status}
                onChange={(event) => setData('status', event.target.checked)}
            />
        </>
    );
}
