import ClientLayout from '@/Layouts/ClientLayout';
import CountryPhoneInput from '@/Components/CountryPhoneInput';
import {
    Head,
    router,
    useForm,
} from '@inertiajs/react';
import {
    CheckCircle2,
    ChevronRight,
    Copy,
    Edit3,
    ExternalLink,
    Gem,
    Globe2,
    Image as ImageIcon,
    Link2,
    Package,
    Plus,
    Search,
    Settings,
    Share2,
    Star,
    Tag,
    Trash2,
    X,
} from 'lucide-react';
import {
    useMemo,
    useState,
} from 'react';


function money(
    value,
    currency = 'INR'
) {
    const n =
        Number(
            value
            ?? 0
        );

    try {
        return new Intl.NumberFormat(
            'en-IN',
            {
                style: 'currency',
                currency:
                    currency
                    || 'INR',

                maximumFractionDigits:
                    2,
            }
        ).format(n);
    } catch {
        return `${currency} ${n.toFixed(2)}`;
    }
}


function Field({
    label,
    error,
    children,
    hint = '',
}) {
    return (
        <div>
            <label className="mb-1 block text-xs font-medium text-neutral-500">
                {label}
            </label>

            {children}

            {hint && (
                <p className="mt-1 text-[10px] text-neutral-400">
                    {hint}
                </p>
            )}

            {error && (
                <p className="mt-1 text-xs text-red-500">
                    {error}
                </p>
            )}
        </div>
    );
}


function Modal({
    title,
    onClose,
    children,
    wide = false,
}) {
    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/55 p-4">
            <div
                className={`max-h-[94vh] w-full overflow-y-auto rounded-2xl bg-white shadow-2xl dark:bg-neutral-900 ${
                    wide
                        ? 'max-w-5xl'
                        : 'max-w-xl'
                }`}
            >
                <div className="sticky top-0 z-20 flex items-center justify-between border-b border-neutral-200 bg-white px-5 py-4 dark:border-neutral-700 dark:bg-neutral-900">
                    <h3 className="font-semibold">
                        {title}
                    </h3>

                    <button
                        type="button"
                        onClick={onClose}
                        className="rounded-lg p-1.5 text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800"
                    >
                        <X className="h-4 w-4" />
                    </button>
                </div>

                <div className="p-5">
                    {children}
                </div>
            </div>
        </div>
    );
}


function StatCard({
    label,
    value,
    icon,
}) {
    return (
        <div className="rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900">
            <div className="flex items-center justify-between">
                <div>
                    <p className="text-[10px] font-semibold uppercase tracking-wider text-neutral-400">
                        {label}
                    </p>

                    <p className="mt-1 text-xl font-semibold">
                        {value}
                    </p>
                </div>

                <div className="rounded-xl bg-neutral-100 p-2.5 text-neutral-500 dark:bg-neutral-800">
                    {icon}
                </div>
            </div>
        </div>
    );
}


function ShareCatalogCard({
    publicCatalog,
    onSettings,
}) {
    const url =
        publicCatalog?.public_url
        ?? '';

    const copy = async () => {
        if (!url) return;

        await navigator.clipboard
            ?.writeText(url);
    };

    const share = () => {
        if (!url) return;

        const text =
            `View our product catalog: ${url}`;

        if (
            navigator.share
        ) {
            navigator.share({
                title:
                    publicCatalog?.title
                    ?? 'Product Catalog',

                text,
                url,
            }).catch(() => {});
            return;
        }

        window.open(
            `https://wa.me/?text=${encodeURIComponent(text)}`,
            '_blank'
        );
    };

    return (
        <div className="overflow-hidden rounded-2xl border border-neutral-200 bg-white dark:border-neutral-700 dark:bg-neutral-900">
            <div className="flex flex-col gap-4 p-5 lg:flex-row lg:items-center">
                <div
                    className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl ${
                        publicCatalog?.is_public
                            ? 'bg-emerald-100 text-emerald-600'
                            : 'bg-amber-100 text-amber-600'
                    }`}
                >
                    <Globe2 className="h-6 w-6" />
                </div>

                <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                        <h2 className="font-semibold">
                            Mini Catalog Share Link
                        </h2>

                        <span
                            className={`rounded-full px-2 py-0.5 text-[10px] font-bold ${
                                publicCatalog?.is_public
                                    ? 'bg-emerald-100 text-emerald-700'
                                    : 'bg-amber-100 text-amber-700'
                            }`}
                        >
                            {publicCatalog?.is_public
                                ? 'LIVE'
                                : 'DRAFT / NOT PUBLISHED'}
                        </span>

                        {publicCatalog?.business_type === 'jewellery' && (
                            <span className="inline-flex items-center gap-1 rounded-full bg-violet-100 px-2 py-0.5 text-[10px] font-bold text-violet-700">
                                <Gem className="h-3 w-3" />
                                JEWELLERY
                            </span>
                        )}
                    </div>

                    <p className="mt-1 text-xs text-neutral-500">
                        Share this link with customers to browse your complete catalog.
                    </p>

                    <div className="mt-3 flex min-w-0 items-center gap-2 rounded-xl bg-neutral-50 p-2 dark:bg-neutral-800">
                        <Link2 className="h-4 w-4 shrink-0 text-neutral-400" />

                        <input
                            readOnly
                            value={url}
                            className="min-w-0 flex-1 bg-transparent text-xs outline-none"
                        />

                        <button
                            type="button"
                            onClick={copy}
                            title="Copy Link"
                            className="rounded-lg border border-neutral-200 bg-white p-2 text-neutral-600 dark:border-neutral-600 dark:bg-neutral-900"
                        >
                            <Copy className="h-4 w-4" />
                        </button>
                    </div>

                    {!publicCatalog?.is_public && (
                        <p className="mt-2 text-[11px] font-medium text-amber-600">
                            Publish Catalog ON karso pachi aa link public open thase.
                        </p>
                    )}
                </div>

                <div className="flex flex-wrap gap-2">
                    <button
                        type="button"
                        onClick={onSettings}
                        className="inline-flex items-center gap-2 rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium dark:border-neutral-600"
                    >
                        <Settings className="h-4 w-4" />
                        Catalog Settings
                    </button>

                    <button
                        type="button"
                        onClick={share}
                        className="inline-flex items-center gap-2 rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium dark:border-neutral-600"
                    >
                        <Share2 className="h-4 w-4" />
                        Share
                    </button>

                    <a
                        href={url}
                        target="_blank"
                        rel="noreferrer"
                        className={`inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white ${
                            publicCatalog?.is_public
                                ? 'bg-brand-600'
                                : 'pointer-events-none bg-neutral-300'
                        }`}
                    >
                        <ExternalLink className="h-4 w-4" />
                        Open Catalog
                    </a>
                </div>
            </div>
        </div>
    );
}


function PublicCatalogSettings({
    settings,
    onClose,
}) {
    const {
        data,
        setData,
        post,
        processing,
        errors,
    } = useForm({
        slug:
            settings?.slug
            ?? '',

        title:
            settings?.title
            ?? 'Product Catalog',

        subtitle:
            settings?.subtitle
            ?? '',

        whatsapp_number:
            settings?.whatsapp_number
            ?? '',

        logo_url:
            settings?.logo_url
            ?? '',

        logo: null,

        accent_color:
            settings?.accent_color
            ?? '#4f46e5',

        business_type:
            settings?.business_type
            ?? 'generic',

        is_public:
            settings?.is_public
            ?? false,

        show_stock:
            settings?.show_stock
            ?? true,

        show_sku:
            settings?.show_sku
            ?? true,

        show_categories:
            settings?.show_categories
            ?? true,
    });


    const submit = (e) => {
        e.preventDefault();

        post(
            route(
                'client.internal-catalog.public-settings'
            ),
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: onClose,
            }
        );
    };


    return (
        <Modal
            wide
            title="Brand & Mini Catalog Settings"
            onClose={onClose}
        >
            <form
                onSubmit={submit}
                className="space-y-5"
            >

                <div className="rounded-2xl border border-neutral-200 p-4 dark:border-neutral-700">
                    <p className="font-semibold">
                        Brand Identity
                    </p>

                    <p className="mt-1 text-[11px] text-neutral-400">
                        This logo and shop name will appear at the top of your public Mini Catalog.
                    </p>

                    <div className="mt-4 grid gap-4 md:grid-cols-2">

                        <Field
                            label="Brand / Shop Name"
                            error={errors.title}
                        >
                            <input
                                value={data.title}
                                onChange={(e) =>
                                    setData(
                                        'title',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                                placeholder="Example: Mohini Jewels"
                            />
                        </Field>


                        <Field
                            label="Catalog Subtitle"
                            error={errors.subtitle}
                        >
                            <input
                                value={data.subtitle}
                                onChange={(e) =>
                                    setData(
                                        'subtitle',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                                placeholder="Premium Jewellery Collection"
                            />
                        </Field>


                        <Field
                            label="Brand Logo Upload"
                            error={errors.logo}
                            hint="PNG/JPG/WebP. Recommended square logo."
                        >
                            <input
                                type="file"
                                accept="image/*"
                                onChange={(e) =>
                                    setData(
                                        'logo',
                                        e.target.files?.[0]
                                        ?? null
                                    )
                                }
                                className="catalog-input"
                            />
                        </Field>


                        <Field
                            label="Brand Logo URL (Optional)"
                            error={errors.logo_url}
                            hint="Upload logo above OR use external logo URL."
                        >
                            <input
                                type="url"
                                value={data.logo_url}
                                onChange={(e) =>
                                    setData(
                                        'logo_url',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                                placeholder="https://..."
                            />
                        </Field>

                    </div>


                    {settings?.logo_url && (
                        <div className="mt-4 flex items-center gap-3 rounded-xl bg-neutral-50 p-3 dark:bg-neutral-800">
                            <img
                                src={settings.logo_url}
                                alt=""
                                className="h-14 w-14 rounded-xl border bg-white object-contain"
                            />

                            <div>
                                <p className="text-xs font-semibold">
                                    Current Brand Logo
                                </p>

                                <p className="mt-1 text-[10px] text-neutral-400">
                                    Upload a new logo to replace it.
                                </p>
                            </div>
                        </div>
                    )}
                </div>


                <div className="grid gap-4 md:grid-cols-2">

                    <Field
                        label="Business Type"
                        error={errors.business_type}
                    >
                        <select
                            value={data.business_type}
                            onChange={(e) =>
                                setData(
                                    'business_type',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="generic">
                                General / Other
                            </option>

                            <option value="jewellery">
                                Jewellery
                            </option>

                            <option value="fashion">
                                Fashion / Apparel
                            </option>

                            <option value="electronics">
                                Electronics
                            </option>

                            <option value="food">
                                Food / Bakery
                            </option>

                            <option value="services">
                                Services
                            </option>
                        </select>
                    </Field>


                    <Field
                        label="Catalog URL Slug"
                        error={errors.slug}
                    >
                        <div className="flex">
                            <span className="rounded-l-lg border border-r-0 border-neutral-300 bg-neutral-50 px-3 py-2.5 text-xs text-neutral-400 dark:border-neutral-600 dark:bg-neutral-800">
                                /c/
                            </span>

                            <input
                                value={data.slug}
                                onChange={(e) =>
                                    setData(
                                        'slug',
                                        e.target.value
                                            .toLowerCase()
                                            .replace(
                                                /[^a-z0-9-]/g,
                                                '-'
                                            )
                                            .replace(
                                                /-+/g,
                                                '-'
                                            )
                                            .replace(
                                                /^-|-$/g,
                                                ''
                                            )
                                    )
                                }
                                className="catalog-input rounded-l-none"
                            />
                        </div>
                    </Field>


                    <Field
                        label="WhatsApp Number"
                        error={errors.whatsapp_number}
                        hint="Country code sathe."
                    >
                        <CountryPhoneInput
                            value={data.whatsapp_number}
                            onChange={(v) => setData('whatsapp_number', v)}
                            defaultCountry="IN"
                            placeholder="Enter WhatsApp number"
                            hint="Select country code, then enter the local number."
                        />
                    </Field>


                    <Field
                        label="Accent Color"
                        error={errors.accent_color}
                    >
                        <div className="flex gap-2">
                            <input
                                type="color"
                                value={data.accent_color}
                                onChange={(e) =>
                                    setData(
                                        'accent_color',
                                        e.target.value
                                    )
                                }
                                className="h-10 w-14 rounded-lg border p-1"
                            />

                            <input
                                value={data.accent_color}
                                onChange={(e) =>
                                    setData(
                                        'accent_color',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                            />
                        </div>
                    </Field>

                </div>


                <div className="grid gap-3 rounded-xl border border-neutral-200 p-4 dark:border-neutral-700 sm:grid-cols-2">

                    {[
                        [
                            'is_public',
                            'Publish Catalog',
                        ],
                        [
                            'show_categories',
                            'Show Categories',
                        ],
                        [
                            'show_stock',
                            'Show Stock',
                        ],
                        [
                            'show_sku',
                            'Show SKU',
                        ],
                    ].map(
                        ([key, label]) => (
                            <label
                                key={key}
                                className="flex items-center gap-2 text-sm"
                            >
                                <input
                                    type="checkbox"
                                    checked={Boolean(
                                        data[key]
                                    )}
                                    onChange={(e) =>
                                        setData(
                                            key,
                                            e.target.checked
                                        )
                                    }
                                />

                                {label}
                            </label>
                        )
                    )}

                </div>


                <div className="flex justify-end gap-2">
                    <button
                        type="button"
                        onClick={onClose}
                        className="rounded-lg border border-neutral-300 px-4 py-2 text-sm"
                    >
                        Cancel
                    </button>

                    <button
                        disabled={processing}
                        className="rounded-lg bg-brand-600 px-5 py-2 text-sm font-medium text-white disabled:opacity-50"
                    >
                        Save Brand & Catalog
                    </button>
                </div>

            </form>
        </Modal>
    );
}


function CategoryModal({
    categories,
    category = null,
    initialParentId = '',
    onClose,
}) {
    const editing =
        Boolean(category);

    const mainCategories =
        categories.filter(
            (c) =>
                !c.parent_id
                && c.id !== category?.id
        );

    const {
        data,
        setData,
        post,
        processing,
        errors,
    } = useForm({
        name:
            category?.name
            ?? '',

        parent_id:
            category?.parent_id
            ?? initialParentId
            ?? '',

        description:
            category?.description
            ?? '',

        thumbnail_url:
            category?.thumbnail_url
            ?? '',

        thumbnail: null,

        is_active:
            category?.is_active
            ?? true,
    });


    const submit = (e) => {
        e.preventDefault();

        post(
            editing
                ? route(
                    'client.internal-catalog.categories.update',
                    category.id
                )
                : route(
                    'client.internal-catalog.categories.store'
                ),
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: onClose,
            }
        );
    };


    return (
        <Modal
            title={
                editing
                    ? 'Edit Category'
                    : data.parent_id
                        ? 'Add Subcategory'
                        : 'Add Category'
            }
            onClose={onClose}
        >
            <form
                onSubmit={submit}
                className="space-y-4"
            >

                <Field
                    label="Category Name"
                    error={errors.name}
                >
                    <input
                        autoFocus
                        value={data.name}
                        onChange={(e) =>
                            setData(
                                'name',
                                e.target.value
                            )
                        }
                        className="catalog-input"
                        placeholder="Example: Rings"
                    />
                </Field>


                <Field
                    label="Parent Category"
                    error={errors.parent_id}
                    hint="Blank = Main Category"
                >
                    <select
                        value={data.parent_id}
                        onChange={(e) =>
                            setData(
                                'parent_id',
                                e.target.value
                            )
                        }
                        className="catalog-input"
                    >
                        <option value="">
                            Main Category
                        </option>

                        {mainCategories.map(
                            (item) => (
                                <option
                                    key={item.id}
                                    value={item.id}
                                >
                                    {item.name}
                                </option>
                            )
                        )}
                    </select>
                </Field>


                <div className="rounded-xl border border-neutral-200 p-4 dark:border-neutral-700">

                    <p className="text-sm font-semibold">
                        Folder Thumbnail
                    </p>

                    <p className="mt-1 text-[10px] text-neutral-400">
                        Thumbnail na hoy to category name pramane suitable icon automatically show thase.
                    </p>


                    <div className="mt-4 grid gap-4">

                        <Field
                            label="Upload Thumbnail"
                            error={errors.thumbnail}
                            hint="Recommended 800×600 or square image."
                        >
                            <input
                                type="file"
                                accept="image/*"
                                onChange={(e) =>
                                    setData(
                                        'thumbnail',
                                        e.target.files?.[0]
                                        ?? null
                                    )
                                }
                                className="catalog-input"
                            />
                        </Field>


                        <Field
                            label="Thumbnail URL (Optional)"
                            error={errors.thumbnail_url}
                        >
                            <input
                                type="url"
                                value={data.thumbnail_url}
                                onChange={(e) =>
                                    setData(
                                        'thumbnail_url',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                                placeholder="https://..."
                            />
                        </Field>


                        {category?.thumbnail_url && (
                            <div className="overflow-hidden rounded-xl border border-neutral-200">
                                <img
                                    src={category.thumbnail_url}
                                    alt=""
                                    className="h-36 w-full object-cover"
                                />
                            </div>
                        )}

                    </div>

                </div>


                <Field
                    label="Description"
                    error={errors.description}
                >
                    <textarea
                        rows={3}
                        value={data.description}
                        onChange={(e) =>
                            setData(
                                'description',
                                e.target.value
                            )
                        }
                        className="catalog-input"
                    />
                </Field>


                <label className="flex items-center gap-2 text-sm">
                    <input
                        type="checkbox"
                        checked={Boolean(
                            data.is_active
                        )}
                        onChange={(e) =>
                            setData(
                                'is_active',
                                e.target.checked
                            )
                        }
                    />

                    Active
                </label>


                <div className="flex justify-end gap-2">
                    <button
                        type="button"
                        onClick={onClose}
                        className="rounded-lg border px-4 py-2 text-sm"
                    >
                        Cancel
                    </button>

                    <button
                        disabled={processing}
                        className="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white"
                    >
                        {editing
                            ? 'Save Category'
                            : data.parent_id
                                ? 'Create Subcategory'
                                : 'Create Category'}
                    </button>
                </div>

            </form>
        </Modal>
    );
}


const jewelleryDefaults = {
    jewellery_type: '',
    metal_type: '',
    purity: '',
    gross_weight_g: '',
    net_weight_g: '',
    diamond_carat: '',
    gemstone_carat: '',
    stone_count: '',
    ring_size: '',
    length_cm: '',
    hallmark_huid: '',
    certificate_no: '',
    making_charges: '',
    gender: '',
    occasion: '',
    price_on_request: false,
    whatsapp_number: '',
    custom_attributes: [],
};


function JewelleryFields({
    attributes,
    setAttributes,
}) {
    const set = (
        key,
        value
    ) => {
        setAttributes({
            ...attributes,
            [key]: value,
        });
    };

    return (
        <div className="md:col-span-2">
            <div className="rounded-2xl border border-violet-200 bg-violet-50/50 p-4 dark:border-violet-900 dark:bg-violet-950/20">
                <div className="mb-4 flex items-center gap-2">
                    <Gem className="h-5 w-5 text-violet-600" />

                    <div>
                        <p className="font-semibold text-violet-800 dark:text-violet-300">
                            Jewellery Details
                        </p>

                        <p className="text-[10px] text-neutral-500">
                            These specifications will also appear on the public mini catalog.
                        </p>
                    </div>
                </div>

                <div className="grid gap-4 md:grid-cols-3">
                    <Field label="Jewellery Type">
                        <select
                            value={attributes.jewellery_type ?? ''}
                            onChange={(e) =>
                                set(
                                    'jewellery_type',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="">
                                Select
                            </option>
                            <option>Ring</option>
                            <option>Necklace</option>
                            <option>Earrings</option>
                            <option>Bangle</option>
                            <option>Bracelet</option>
                            <option>Pendant</option>
                            <option>Chain</option>
                            <option>Mangalsutra</option>
                            <option>Nose Pin</option>
                            <option>Anklet</option>
                            <option>Other</option>
                        </select>
                    </Field>

                    <Field label="Metal">
                        <select
                            value={attributes.metal_type ?? ''}
                            onChange={(e) =>
                                set(
                                    'metal_type',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="">
                                Select
                            </option>
                            <option>Gold</option>
                            <option>Silver</option>
                            <option>Platinum</option>
                            <option>Rose Gold</option>
                            <option>White Gold</option>
                            <option>Other</option>
                        </select>
                    </Field>

                    <Field label="Purity / Karat">
                        <select
                            value={attributes.purity ?? ''}
                            onChange={(e) =>
                                set(
                                    'purity',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="">
                                Select
                            </option>
                            <option>24K</option>
                            <option>22K</option>
                            <option>18K</option>
                            <option>14K</option>
                            <option>10K</option>
                            <option>925 Silver</option>
                            <option>950 Platinum</option>
                            <option>Other</option>
                        </select>
                    </Field>

                    <Field label="Gross Weight (g)">
                        <input
                            type="number"
                            step="0.001"
                            value={attributes.gross_weight_g ?? ''}
                            onChange={(e) =>
                                set(
                                    'gross_weight_g',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Net Weight (g)">
                        <input
                            type="number"
                            step="0.001"
                            value={attributes.net_weight_g ?? ''}
                            onChange={(e) =>
                                set(
                                    'net_weight_g',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Diamond Carat">
                        <input
                            type="number"
                            step="0.001"
                            value={attributes.diamond_carat ?? ''}
                            onChange={(e) =>
                                set(
                                    'diamond_carat',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Gemstone Carat">
                        <input
                            type="number"
                            step="0.001"
                            value={attributes.gemstone_carat ?? ''}
                            onChange={(e) =>
                                set(
                                    'gemstone_carat',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Stone Count">
                        <input
                            type="number"
                            min="0"
                            value={attributes.stone_count ?? ''}
                            onChange={(e) =>
                                set(
                                    'stone_count',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Ring / Product Size">
                        <input
                            value={attributes.ring_size ?? ''}
                            onChange={(e) =>
                                set(
                                    'ring_size',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Length (cm)">
                        <input
                            type="number"
                            step="0.01"
                            value={attributes.length_cm ?? ''}
                            onChange={(e) =>
                                set(
                                    'length_cm',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Hallmark / HUID">
                        <input
                            value={attributes.hallmark_huid ?? ''}
                            onChange={(e) =>
                                set(
                                    'hallmark_huid',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Certificate No.">
                        <input
                            value={attributes.certificate_no ?? ''}
                            onChange={(e) =>
                                set(
                                    'certificate_no',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field label="Making Charges">
                        <input
                            value={attributes.making_charges ?? ''}
                            onChange={(e) =>
                                set(
                                    'making_charges',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                            placeholder="Example: ₹850/g or 10%"
                        />
                    </Field>

                    <Field label="Gender">
                        <select
                            value={attributes.gender ?? ''}
                            onChange={(e) =>
                                set(
                                    'gender',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="">
                                Select
                            </option>
                            <option>Women</option>
                            <option>Men</option>
                            <option>Unisex</option>
                            <option>Kids</option>
                        </select>
                    </Field>

                    <Field label="Occasion">
                        <input
                            value={attributes.occasion ?? ''}
                            onChange={(e) =>
                                set(
                                    'occasion',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                            placeholder="Wedding, Daily Wear..."
                        />
                    </Field>
                </div>

                <label className="mt-4 flex items-center gap-2 text-sm font-medium">
                    <input
                        type="checkbox"
                        checked={Boolean(
                            attributes.price_on_request
                        )}
                        onChange={(e) =>
                            set(
                                'price_on_request',
                                e.target.checked
                            )
                        }
                    />

                    Price on Request
                </label>


                {Boolean(
                    attributes.price_on_request
                ) && (
                    <div className="mt-4">
                        <Field
                            label="WhatsApp Number for Price Enquiry"
                            hint="Optional. Country code select karo ane local WhatsApp number lakho. Blank rakhso to Mini Catalog main WhatsApp number use thase."
                        >
                            <input
                                type="tel"
                                value={
                                    attributes.whatsapp_number
                                    ?? ''
                                }
                                onChange={(e) =>
                                    set(
                                        'whatsapp_number',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                                placeholder="Example: 919876543210"
                            />
                        </Field>
                    </div>
                )}
            </div>
        </div>
    );
}


function CustomAttributes({
    attributes,
    setAttributes,
}) {
    const items =
        attributes.custom_attributes
        ?? [];

    const update = (
        index,
        key,
        value
    ) => {
        const next =
            [...items];

        next[index] = {
            ...next[index],
            [key]: value,
        };

        setAttributes({
            ...attributes,
            custom_attributes:
                next,
        });
    };

    const add = () => {
        setAttributes({
            ...attributes,
            custom_attributes: [
                ...items,
                {
                    name: '',
                    value: '',
                },
            ],
        });
    };

    const remove = (
        index
    ) => {
        setAttributes({
            ...attributes,
            custom_attributes:
                items.filter(
                    (_, i) =>
                        i !== index
                ),
        });
    };

    return (
        <div className="md:col-span-2 rounded-xl border border-neutral-200 p-4 dark:border-neutral-700">
            <div className="flex items-center justify-between">
                <div>
                    <p className="text-sm font-semibold">
                        Custom Product Specifications
                    </p>

                    <p className="text-[10px] text-neutral-400">
                        Any business can add extra specification fields.
                    </p>
                </div>

                <button
                    type="button"
                    onClick={add}
                    className="inline-flex items-center gap-1 rounded-lg border px-3 py-2 text-xs"
                >
                    <Plus className="h-3.5 w-3.5" />
                    Add Field
                </button>
            </div>

            {items.length > 0 && (
                <div className="mt-3 space-y-2">
                    {items.map(
                        (
                            item,
                            index
                        ) => (
                            <div
                                key={index}
                                className="grid gap-2 sm:grid-cols-[1fr_1fr_auto]"
                            >
                                <input
                                    value={item.name ?? ''}
                                    onChange={(e) =>
                                        update(
                                            index,
                                            'name',
                                            e.target.value
                                        )
                                    }
                                    className="catalog-input"
                                    placeholder="Example: Diamond Color"
                                />

                                <input
                                    value={item.value ?? ''}
                                    onChange={(e) =>
                                        update(
                                            index,
                                            'value',
                                            e.target.value
                                        )
                                    }
                                    className="catalog-input"
                                    placeholder="Example: EF"
                                />

                                <button
                                    type="button"
                                    onClick={() =>
                                        remove(
                                            index
                                        )
                                    }
                                    className="rounded-lg p-2 text-red-500"
                                >
                                    <Trash2 className="h-4 w-4" />
                                </button>
                            </div>
                        )
                    )}
                </div>
            )}
        </div>
    );
}


function ProductModal({
    categories,
    businessType,
    product = null,
    onClose,
}) {
    const editing =
        Boolean(product);

    const initialAttributes = {
        ...jewelleryDefaults,
        ...(product?.attributes_json
            ?? {}),
    };

    const [
        attributes,
        setAttributes,
    ] = useState(
        initialAttributes
    );

    const {
        data,
        setData,
        post,
        processing,
        errors,
    } = useForm({
        category_id:
            product?.category_id
            ?? '',

        name:
            product?.name
            ?? '',

        sku:
            product?.sku
            ?? '',

        description:
            product?.description
            ?? '',

        regular_price:
            product?.regular_price
            ?? '',

        sale_price:
            product?.sale_price
            ?? '',

        currency:
            product?.currency
            ?? 'INR',

        stock:
            product?.stock
            ?? 0,

        availability:
            product?.availability
            ?? 'in_stock',

        image: null,

        image_url:
            product?.raw_image_url
            ?? '',

        product_url:
            product?.product_url
            ?? '',

        is_featured:
            product?.is_featured
            ?? false,

        is_active:
            product?.is_active
            ?? true,

        attributes_json: '',
    });

    const categoryOptions =
        useMemo(
            () => {
                const mains =
                    categories.filter(
                        (c) =>
                            !c.parent_id
                    );

                const out = [];

                mains.forEach(
                    (main) => {
                        out.push({
                            id:
                                main.id,

                            label:
                                main.name,
                        });

                        categories
                            .filter(
                                (c) =>
                                    String(
                                        c.parent_id
                                    )
                                    === String(
                                        main.id
                                    )
                            )
                            .forEach(
                                (child) =>
                                    out.push({
                                        id:
                                            child.id,

                                        label:
                                            `${main.name} › ${child.name}`,
                                    })
                            );
                    }
                );

                return out;
            },
            [categories]
        );

    const submit = (e) => {
        e.preventDefault();

        data.attributes_json =
            JSON.stringify(
                attributes
            );

        post(
            editing
                ? route(
                    'client.internal-catalog.products.update',
                    product.id
                )
                : route(
                    'client.internal-catalog.products.store'
                ),
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: onClose,
            }
        );
    };

    return (
        <Modal
            wide
            title={
                editing
                    ? 'Edit Product'
                    : 'Add Product'
            }
            onClose={onClose}
        >
            <form onSubmit={submit}>
                <div className="grid gap-4 md:grid-cols-2">
                    <Field
                        label="Product Name"
                        error={errors.name}
                    >
                        <input
                            autoFocus
                            value={data.name}
                            onChange={(e) =>
                                setData(
                                    'name',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field
                        label="SKU / Product Code"
                        error={errors.sku}
                    >
                        <input
                            value={data.sku}
                            onChange={(e) =>
                                setData(
                                    'sku',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field
                        label="Category / Subcategory"
                        error={errors.category_id}
                    >
                        <select
                            value={data.category_id}
                            onChange={(e) =>
                                setData(
                                    'category_id',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="">
                                Uncategorized
                            </option>

                            {categoryOptions.map(
                                (item) => (
                                    <option
                                        key={item.id}
                                        value={item.id}
                                    >
                                        {item.label}
                                    </option>
                                )
                            )}
                        </select>
                    </Field>

                    <Field
                        label="Availability"
                        error={errors.availability}
                    >
                        <select
                            value={data.availability}
                            onChange={(e) =>
                                setData(
                                    'availability',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        >
                            <option value="in_stock">
                                In Stock
                            </option>

                            <option value="out_of_stock">
                                Out of Stock
                            </option>

                            <option value="preorder">
                                Preorder
                            </option>
                        </select>
                    </Field>

                    <Field
                        label="Regular Price"
                        error={errors.regular_price}
                    >
                        <input
                            type="number"
                            min="0"
                            step="0.01"
                            value={data.regular_price}
                            onChange={(e) =>
                                setData(
                                    'regular_price',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field
                        label="Sale Price"
                        error={errors.sale_price}
                    >
                        <input
                            type="number"
                            min="0"
                            step="0.01"
                            value={data.sale_price}
                            onChange={(e) =>
                                setData(
                                    'sale_price',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                            placeholder="Optional"
                        />
                    </Field>

                    <Field
                        label="Currency"
                        error={errors.currency}
                    >
                        <input
                            value={data.currency}
                            maxLength={3}
                            onChange={(e) =>
                                setData(
                                    'currency',
                                    e.target.value
                                        .toUpperCase()
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field
                        label="Stock Quantity"
                        error={errors.stock}
                    >
                        <input
                            type="number"
                            min="0"
                            value={data.stock}
                            onChange={(e) =>
                                setData(
                                    'stock',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field
                        label="Product Image"
                        error={errors.image}
                    >
                        <input
                            type="file"
                            accept="image/*"
                            onChange={(e) =>
                                setData(
                                    'image',
                                    e.target.files?.[0]
                                    ?? null
                                )
                            }
                            className="catalog-input"
                        />
                    </Field>

                    <Field
                        label="External Image URL"
                        error={errors.image_url}
                    >
                        <input
                            type="url"
                            value={data.image_url}
                            onChange={(e) =>
                                setData(
                                    'image_url',
                                    e.target.value
                                )
                            }
                            className="catalog-input"
                            placeholder="https://..."
                        />
                    </Field>

                    <div className="md:col-span-2">
                        <Field
                            label="Product URL"
                            error={errors.product_url}
                        >
                            <input
                                type="url"
                                value={data.product_url}
                                onChange={(e) =>
                                    setData(
                                        'product_url',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                                placeholder="Optional"
                            />
                        </Field>
                    </div>

                    <div className="md:col-span-2">
                        <Field
                            label="Description"
                            error={errors.description}
                        >
                            <textarea
                                rows={4}
                                value={data.description}
                                onChange={(e) =>
                                    setData(
                                        'description',
                                        e.target.value
                                    )
                                }
                                className="catalog-input"
                            />
                        </Field>
                    </div>

                    {businessType === 'jewellery' && (
                        <JewelleryFields
                            attributes={attributes}
                            setAttributes={
                                setAttributes
                            }
                        />
                    )}

                    <CustomAttributes
                        attributes={attributes}
                        setAttributes={
                            setAttributes
                        }
                    />
                </div>

                <div className="mt-5 flex flex-wrap gap-5">
                    <label className="flex items-center gap-2 text-sm">
                        <input
                            type="checkbox"
                            checked={Boolean(
                                data.is_featured
                            )}
                            onChange={(e) =>
                                setData(
                                    'is_featured',
                                    e.target.checked
                                )
                            }
                        />
                        Featured Product
                    </label>

                    <label className="flex items-center gap-2 text-sm">
                        <input
                            type="checkbox"
                            checked={Boolean(
                                data.is_active
                            )}
                            onChange={(e) =>
                                setData(
                                    'is_active',
                                    e.target.checked
                                )
                            }
                        />
                        Active Product
                    </label>
                </div>

                <div className="mt-6 flex justify-end gap-2">
                    <button
                        type="button"
                        onClick={onClose}
                        className="rounded-lg border px-4 py-2 text-sm"
                    >
                        Cancel
                    </button>

                    <button
                        disabled={processing}
                        className="rounded-lg bg-brand-600 px-5 py-2 text-sm font-medium text-white"
                    >
                        {editing
                            ? 'Save Product'
                            : 'Create Product'}
                    </button>
                </div>
            </form>
        </Modal>
    );
}


export default function CatalogIndex({
    categories = [],
    products,
    stats = {},
    filters = {},
    publicCatalog = null,
}) {
    const [
        showSettings,
        setShowSettings,
    ] = useState(false);

    const [
        showCategory,
        setShowCategory,
    ] = useState(false);

    const [
        editCategory,
        setEditCategory,
    ] = useState(null);

    const [
        showProduct,
        setShowProduct,
    ] = useState(false);

    const [
        editProduct,
        setEditProduct,
    ] = useState(null);

    const [
        query,
        setQuery,
    ] = useState(
        filters.q
        ?? ''
    );

    const mainCategories =
        categories.filter(
            (c) =>
                !c.parent_id
        );

    const categoryDisplay =
        useMemo(() => {
            const byId =
                Object.fromEntries(
                    categories.map(
                        (c) => [
                            String(c.id),
                            c,
                        ]
                    )
                );

            return categories.map(
                (c) => ({
                    ...c,

                    display:
                        c.parent_id
                        && byId[
                            String(
                                c.parent_id
                            )
                        ]
                            ? `${byId[String(c.parent_id)].name} › ${c.name}`
                            : c.name,
                })
            );
        }, [categories]);

    const applyFilters = (
        extra = {}
    ) => {
        router.get(
            route(
                'client.internal-catalog.index'
            ),
            {
                q:
                    query
                    || undefined,

                category:
                    filters.category
                    || undefined,

                status:
                    filters.status
                    || undefined,

                featured:
                    filters.featured
                    || undefined,

                ...extra,
            },
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            }
        );
    };

    const deleteCategory = (
        category
    ) => {
        if (
            !confirm(
                `Delete "${category.name}"?`
            )
        ) {
            return;
        }

        router.delete(
            route(
                'client.internal-catalog.categories.destroy',
                category.id
            ),
            {
                preserveScroll: true,
            }
        );
    };

    const deleteProduct = (
        product
    ) => {
        if (
            !confirm(
                `Delete "${product.name}"?`
            )
        ) {
            return;
        }

        router.delete(
            route(
                'client.internal-catalog.products.destroy',
                product.id
            ),
            {
                preserveScroll: true,
            }
        );
    };

    const toggleProduct = (
        product
    ) => {
        router.post(
            route(
                'client.internal-catalog.products.toggle',
                product.id
            ),
            {},
            {
                preserveScroll: true,
            }
        );
    };

    return (
        <ClientLayout title="Product Catalog">
            <Head title="Product Catalog" />

            <style>{`
                .catalog-input {
                    width: 100%;
                    border-radius: .65rem;
                    border: 1px solid rgb(212 212 212);
                    background: white;
                    padding: .62rem .75rem;
                    font-size: .875rem;
                    outline: none;
                }

                .catalog-input:focus {
                    border-color: rgb(99 102 241);
                    box-shadow: 0 0 0 2px rgb(99 102 241 / .10);
                }

                .dark .catalog-input {
                    border-color: rgb(82 82 82);
                    background: rgb(38 38 38);
                }
            `}</style>

            <div className="mx-auto max-w-7xl space-y-5">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <h1 className="text-2xl font-semibold">
                            Product Catalog
                        </h1>

                        <p className="mt-1 text-sm text-neutral-500">
                            Manage products, categories, subcategories and your shareable mini catalog.
                        </p>
                    </div>

                    <div className="flex flex-wrap gap-2">
                        <button
                            type="button"
                            onClick={() =>
                                setShowCategory(
                                    true
                                )
                            }
                            className="inline-flex items-center gap-2 rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium dark:border-neutral-600"
                        >
                            <Tag className="h-4 w-4" />
                            Add Category
                        </button>

                        <button
                            type="button"
                            onClick={() =>
                                setShowProduct(
                                    true
                                )
                            }
                            className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white"
                        >
                            <Plus className="h-4 w-4" />
                            Add Product
                        </button>
                    </div>
                </div>


                <ShareCatalogCard
                    publicCatalog={
                        publicCatalog
                    }
                    onSettings={() =>
                        setShowSettings(
                            true
                        )
                    }
                />


                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
                    <StatCard
                        label="Products"
                        value={stats.products ?? 0}
                        icon={
                            <Package className="h-5 w-5" />
                        }
                    />

                    <StatCard
                        label="Active"
                        value={stats.active_products ?? 0}
                        icon={
                            <CheckCircle2 className="h-5 w-5" />
                        }
                    />

                    <StatCard
                        label="Featured"
                        value={stats.featured_products ?? 0}
                        icon={
                            <Star className="h-5 w-5" />
                        }
                    />

                    <StatCard
                        label="Categories"
                        value={stats.categories ?? 0}
                        icon={
                            <Tag className="h-5 w-5" />
                        }
                    />

                    <StatCard
                        label="Subcategories"
                        value={stats.subcategories ?? 0}
                        icon={
                            <ChevronRight className="h-5 w-5" />
                        }
                    />
                </div>


                <div className="rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900">
                    <div className="flex flex-wrap gap-2">
                        <div className="relative min-w-[220px] flex-1">
                            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral-400" />

                            <input
                                value={query}
                                onChange={(e) =>
                                    setQuery(
                                        e.target.value
                                    )
                                }
                                onKeyDown={(e) => {
                                    if (
                                        e.key
                                        === 'Enter'
                                    ) {
                                        applyFilters();
                                    }
                                }}
                                placeholder="Search product, SKU..."
                                className="catalog-input pl-9"
                            />
                        </div>

                        <select
                            value={
                                filters.category
                                ?? ''
                            }
                            onChange={(e) =>
                                applyFilters({
                                    category:
                                        e.target.value
                                        || undefined,
                                })
                            }
                            className="catalog-input w-auto min-w-[210px]"
                        >
                            <option value="">
                                All Categories
                            </option>

                            {categoryDisplay.map(
                                (category) => (
                                    <option
                                        key={category.id}
                                        value={category.id}
                                    >
                                        {category.display}
                                    </option>
                                )
                            )}
                        </select>

                        <select
                            value={
                                filters.status
                                ?? ''
                            }
                            onChange={(e) =>
                                applyFilters({
                                    status:
                                        e.target.value
                                        || undefined,
                                })
                            }
                            className="catalog-input w-auto"
                        >
                            <option value="">
                                All Status
                            </option>

                            <option value="active">
                                Active
                            </option>

                            <option value="inactive">
                                Inactive
                            </option>
                        </select>

                        <button
                            type="button"
                            onClick={() =>
                                applyFilters({
                                    featured:
                                        filters.featured
                                        === '1'
                                            ? undefined
                                            : '1',
                                })
                            }
                            className={`rounded-lg border px-3 py-2 text-sm ${
                                filters.featured
                                === '1'
                                    ? 'border-amber-300 bg-amber-50 text-amber-700'
                                    : 'border-neutral-300 dark:border-neutral-600'
                            }`}
                        >
                            ★ Featured
                        </button>
                    </div>
                </div>


                <div className="rounded-xl border border-neutral-200 bg-white p-4 dark:border-neutral-700 dark:bg-neutral-900">
                    <div className="mb-4 flex items-center justify-between">
                        <div>
                            <h2 className="font-semibold">
                                Categories & Subcategories
                            </h2>

                            <p className="text-[11px] text-neutral-400">
                                Example: Jewellery → Rings → product.
                            </p>
                        </div>
                    </div>

                    {mainCategories.length === 0 ? (
                        <div className="rounded-xl border border-dashed py-8 text-center text-sm text-neutral-400">
                            No categories yet.
                        </div>
                    ) : (
                        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                            {mainCategories.map(
                                (main) => {
                                    const children =
                                        categories.filter(
                                            (c) =>
                                                String(
                                                    c.parent_id
                                                )
                                                === String(
                                                    main.id
                                                )
                                        );

                                    return (
                                        <div
                                            key={main.id}
                                            className="rounded-xl border border-neutral-200 p-3 dark:border-neutral-700"
                                        >
                                            <div className="flex items-start justify-between gap-2">
                                                <div>
                                                    <p className="font-semibold">
                                                        {main.name}
                                                    </p>

                                                    <p className="text-[10px] text-neutral-400">
                                                        {main.products_count ?? 0} direct product(s)
                                                    </p>
                                                </div>

                                                <div className="flex gap-1">
                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            setEditCategory(
                                                                main
                                                            )
                                                        }
                                                        className="p-1.5 text-neutral-400 hover:text-brand-600"
                                                    >
                                                        <Edit3 className="h-3.5 w-3.5" />
                                                    </button>

                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            deleteCategory(
                                                                main
                                                            )
                                                        }
                                                        className="p-1.5 text-neutral-400 hover:text-red-500"
                                                    >
                                                        <Trash2 className="h-3.5 w-3.5" />
                                                    </button>
                                                </div>
                                            </div>

                                            <div className="mt-3 space-y-1.5">
                                                {children.map(
                                                    (child) => (
                                                        <div
                                                            key={child.id}
                                                            className="flex items-center justify-between rounded-lg bg-neutral-50 px-3 py-2 dark:bg-neutral-800"
                                                        >
                                                            <div className="flex items-center gap-2">
                                                                <ChevronRight className="h-3.5 w-3.5 text-neutral-400" />

                                                                <div>
                                                                    <p className="text-xs font-medium">
                                                                        {child.name}
                                                                    </p>

                                                                    <p className="text-[9px] text-neutral-400">
                                                                        {child.products_count ?? 0} product(s)
                                                                    </p>
                                                                </div>
                                                            </div>

                                                            <div className="flex">
                                                                <button
                                                                    type="button"
                                                                    onClick={() =>
                                                                        setEditCategory(
                                                                            child
                                                                        )
                                                                    }
                                                                    className="p-1 text-neutral-400"
                                                                >
                                                                    <Edit3 className="h-3 w-3" />
                                                                </button>

                                                                <button
                                                                    type="button"
                                                                    onClick={() =>
                                                                        deleteCategory(
                                                                            child
                                                                        )
                                                                    }
                                                                    className="p-1 text-red-400"
                                                                >
                                                                    <Trash2 className="h-3 w-3" />
                                                                </button>
                                                            </div>
                                                        </div>
                                                    )
                                                )}

                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        setEditCategory({
                                                            parent_id:
                                                                main.id,

                                                            name: '',

                                                            description: '',

                                                            is_active:
                                                                true,

                                                            __new:
                                                                true,
                                                        })
                                                    }
                                                    className="mt-1 flex w-full items-center justify-center gap-1 rounded-lg border border-dashed px-3 py-2 text-[11px] text-neutral-500"
                                                >
                                                    <Plus className="h-3 w-3" />
                                                    Add Subcategory
                                                </button>
                                            </div>
                                        </div>
                                    );
                                }
                            )}
                        </div>
                    )}
                </div>


                {products?.data?.length ? (
                    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                        {products.data.map(
                            (product) => {
                                const attrs =
                                    product.attributes_json
                                    ?? {};

                                const priceOnRequest =
                                    Boolean(
                                        attrs.price_on_request
                                    );

                                const sellingPrice =
                                    product.sale_price !== null
                                    && product.sale_price !== ''
                                        ? product.sale_price
                                        : product.regular_price;

                                return (
                                    <div
                                        key={product.id}
                                        className="overflow-hidden rounded-2xl border border-neutral-200 bg-white dark:border-neutral-700 dark:bg-neutral-900"
                                    >
                                        <div className="relative aspect-[16/10] bg-neutral-100 dark:bg-neutral-800">
                                            {product.image_url ? (
                                                <img
                                                    src={product.image_url}
                                                    alt={product.name}
                                                    className="h-full w-full object-cover"
                                                />
                                            ) : (
                                                <div className="flex h-full items-center justify-center">
                                                    <ImageIcon className="h-10 w-10 text-neutral-300" />
                                                </div>
                                            )}

                                            <div className="absolute left-3 top-3 flex gap-1">
                                                {product.is_featured && (
                                                    <span className="rounded-full bg-amber-100 px-2 py-1 text-[9px] font-bold text-amber-700">
                                                        FEATURED
                                                    </span>
                                                )}

                                                <span
                                                    className={`rounded-full px-2 py-1 text-[9px] font-bold ${
                                                        product.is_active
                                                            ? 'bg-emerald-100 text-emerald-700'
                                                            : 'bg-neutral-200 text-neutral-600'
                                                    }`}
                                                >
                                                    {product.is_active
                                                        ? 'ACTIVE'
                                                        : 'INACTIVE'}
                                                </span>
                                            </div>
                                        </div>

                                        <div className="p-4">
                                            <div className="flex justify-between gap-3">
                                                <div className="min-w-0">
                                                    <p className="truncate font-semibold">
                                                        {product.name}
                                                    </p>

                                                    <p className="mt-0.5 truncate text-[10px] text-neutral-400">
                                                        {product.category
                                                            ?? 'Uncategorized'}

                                                        {product.sku
                                                            ? ` · ${product.sku}`
                                                            : ''}
                                                    </p>
                                                </div>

                                                <div className="text-right">
                                                    <p className="font-semibold text-brand-600">
                                                        {priceOnRequest
                                                            ? 'Price on Request'
                                                            : money(
                                                                sellingPrice,
                                                                product.currency
                                                            )}
                                                    </p>
                                                </div>
                                            </div>

                                            {publicCatalog?.business_type === 'jewellery' && (
                                                <div className="mt-3 flex flex-wrap gap-1">
                                                    {attrs.metal_type && (
                                                        <span className="rounded bg-violet-50 px-2 py-1 text-[9px] text-violet-700">
                                                            {attrs.metal_type}
                                                        </span>
                                                    )}

                                                    {attrs.purity && (
                                                        <span className="rounded bg-violet-50 px-2 py-1 text-[9px] text-violet-700">
                                                            {attrs.purity}
                                                        </span>
                                                    )}

                                                    {attrs.gross_weight_g && (
                                                        <span className="rounded bg-neutral-100 px-2 py-1 text-[9px]">
                                                            {attrs.gross_weight_g} g
                                                        </span>
                                                    )}

                                                    {attrs.diamond_carat && (
                                                        <span className="rounded bg-neutral-100 px-2 py-1 text-[9px]">
                                                            {attrs.diamond_carat} ct
                                                        </span>
                                                    )}
                                                </div>
                                            )}

                                            <div className="mt-3 flex items-center justify-between text-xs">
                                                <span
                                                    className={
                                                        product.availability
                                                        === 'in_stock'
                                                            ? 'text-emerald-600'
                                                            : 'text-red-500'
                                                    }
                                                >
                                                    {product.availability
                                                    === 'in_stock'
                                                        ? 'In Stock'
                                                        : product.availability
                                                        === 'preorder'
                                                            ? 'Preorder'
                                                            : 'Out of Stock'}
                                                </span>

                                                <span className="text-neutral-400">
                                                    Stock: {product.stock}
                                                </span>
                                            </div>

                                            <div className="mt-4 flex gap-2">
                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        setEditProduct(
                                                            product
                                                        )
                                                    }
                                                    className="flex-1 rounded-lg border px-3 py-2 text-xs"
                                                >
                                                    Edit
                                                </button>

                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        toggleProduct(
                                                            product
                                                        )
                                                    }
                                                    className="flex-1 rounded-lg border px-3 py-2 text-xs"
                                                >
                                                    {product.is_active
                                                        ? 'Disable'
                                                        : 'Enable'}
                                                </button>

                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        deleteProduct(
                                                            product
                                                        )
                                                    }
                                                    className="rounded-lg p-2 text-red-500"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                );
                            }
                        )}
                    </div>
                ) : (
                    <div className="rounded-2xl border border-dashed py-14 text-center text-neutral-400">
                        No products yet.
                    </div>
                )}
            </div>


            {showSettings && (
                <PublicCatalogSettings
                    settings={publicCatalog}
                    onClose={() =>
                        setShowSettings(
                            false
                        )
                    }
                />
            )}


            {showCategory && (
                <CategoryModal
                    categories={categories}
                    onClose={() =>
                        setShowCategory(
                            false
                        )
                    }
                />
            )}


            {editCategory && (
                editCategory.__new ? (
                    <CategoryModal
                        categories={categories}
                        category={null}
                        initialParentId={editCategory.parent_id}
                        onClose={() =>
                            setEditCategory(
                                null
                            )
                        }
                    />
                ) : (
                    <CategoryModal
                        categories={categories}
                        category={editCategory}
                        onClose={() =>
                            setEditCategory(
                                null
                            )
                        }
                    />
                )
            )}


            {showProduct && (
                <ProductModal
                    categories={categories}
                    businessType={
                        publicCatalog?.business_type
                        ?? 'generic'
                    }
                    onClose={() =>
                        setShowProduct(
                            false
                        )
                    }
                />
            )}


            {editProduct && (
                <ProductModal
                    categories={categories}
                    businessType={
                        publicCatalog?.business_type
                        ?? 'generic'
                    }
                    product={editProduct}
                    onClose={() =>
                        setEditProduct(
                            null
                        )
                    }
                />
            )}
        </ClientLayout>
    );
}
