import { Head, router, useForm } from '@inertiajs/react';
import {
    Boxes,
    Plus,
    Save,
    Trash2,
    ShieldCheck,
    Globe2,
    Star,
} from 'lucide-react';
import WhiteLabelAdminLayout, {
    FlashMessages,
    cardClass,
    fieldClass,
} from '@/Layouts/WhiteLabelAdminLayout';

const emptyPlan = {
    name: '',
    slug: '',
    description: '',
    currency_code: 'INR',
    monthly_price: '0',
    yearly_price: '0',
    trial_days: '0',
    features_text: '',
    limits_json: '{}',
    is_active: true,
    show_on_website: true,
    is_featured: false,
    public_sort_order: '0',
    cta_text: 'Get Started',
    export_enabled: false,
    custom_domain_enabled: false,
};

function Toggle({
    checked,
    onChange,
    label,
    hint,
    icon: Icon,
}) {
    return (
        <label className="flex min-w-[220px] items-start gap-3 rounded-[11px] border border-[#34363a] bg-[#17181a] p-3">
            <input
                type="checkbox"
                checked={checked}
                onChange={(e) => onChange(e.target.checked)}
                className="mt-1"
            />
            <div className="min-w-0">
                <div className="flex items-center gap-2 text-sm font-semibold text-[#e5e7eb]">
                    {Icon && <Icon className="h-4 w-4 text-[#7eaf67]" />}
                    {label}
                </div>
                {hint && (
                    <div className="mt-1 text-xs leading-relaxed text-[#777c83]">
                        {hint}
                    </div>
                )}
            </div>
        </label>
    );
}

function PlanEditor({ plan, currency }) {
    const form = useForm({
        name: plan.name || '',
        slug: (plan.slug || '').replace(/^wl-\d+-/, ''),
        description: plan.description || '',
        currency_code:
            plan.currency_code
            || currency
            || 'INR',
        monthly_price:
            plan.monthly_price
            || '0',
        yearly_price:
            plan.yearly_price
            || '0',
        trial_days:
            String(plan.trial_days ?? 0),
        features_text:
            plan.features_text
            || '',
        limits_json:
            plan.limits_json
            || '{}',
        is_active:
            !!plan.is_active,
        show_on_website:
            !!plan.show_on_website,
        is_featured:
            !!plan.is_featured,
        public_sort_order:
            String(
                plan.public_sort_order
                ?? 0
            ),
        cta_text:
            plan.cta_text
            || 'Get Started',
        export_enabled:
            !!plan.export_enabled,
        custom_domain_enabled:
            !!plan.custom_domain_enabled,
    });

    return (
        <form
            onSubmit={(e) => {
                e.preventDefault();

                form.put(
                    route(
                        'white-label.admin.plans.update',
                        plan.id
                    ),
                    {
                        preserveScroll: true,
                    }
                );
            }}
            className={cardClass}
        >
            <div className="mb-5 flex flex-wrap items-start justify-between gap-4">
                <div>
                    <div className="flex flex-wrap items-center gap-2">
                        <h3 className="text-lg font-semibold text-white">
                            {plan.name}
                        </h3>

                        {plan.show_on_website && (
                            <span className="rounded-full border border-[#345d2c] bg-[#172513] px-2.5 py-1 text-[11px] font-semibold text-[#9ed486]">
                                LIVE ON WEBSITE
                            </span>
                        )}

                        {plan.is_featured && (
                            <span className="rounded-full border border-amber-700/50 bg-amber-950/30 px-2.5 py-1 text-[11px] font-semibold text-amber-300">
                                FEATURED
                            </span>
                        )}
                    </div>

                    <div className="mt-1 text-xs text-[#858a91]">
                        {plan.assigned_clients} active client assignment(s)
                    </div>
                </div>

                <div className="text-right text-xs text-[#73787f]">
                    Website order
                    <div className="mt-0.5 text-sm font-semibold text-[#d1d4d8]">
                        {plan.public_sort_order ?? 0}
                    </div>
                </div>
            </div>

            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                <input
                    className={fieldClass}
                    value={form.data.name}
                    onChange={(e) =>
                        form.setData(
                            'name',
                            e.target.value
                        )
                    }
                    placeholder="Plan name"
                    required
                />

                <input
                    className={fieldClass}
                    value={form.data.slug}
                    onChange={(e) =>
                        form.setData(
                            'slug',
                            e.target.value
                        )
                    }
                    placeholder="Slug"
                />

                <input
                    className={fieldClass}
                    value={form.data.currency_code}
                    onChange={(e) =>
                        form.setData(
                            'currency_code',
                            e.target.value.toUpperCase()
                        )
                    }
                    placeholder="Currency"
                    required
                />

                <input
                    className={fieldClass}
                    type="number"
                    min="0"
                    max="3650"
                    value={form.data.trial_days}
                    onChange={(e) =>
                        form.setData(
                            'trial_days',
                            e.target.value
                        )
                    }
                    placeholder="Trial days"
                    required
                />

                <div className="grid grid-cols-2 gap-2 xl:col-span-2">
                    <input
                        className={fieldClass}
                        type="number"
                        min="0"
                        step="0.01"
                        value={
                            form.data.monthly_price
                        }
                        onChange={(e) =>
                            form.setData(
                                'monthly_price',
                                e.target.value
                            )
                        }
                        placeholder="Monthly price"
                        required
                    />

                    <input
                        className={fieldClass}
                        type="number"
                        min="0"
                        step="0.01"
                        value={
                            form.data.yearly_price
                        }
                        onChange={(e) =>
                            form.setData(
                                'yearly_price',
                                e.target.value
                            )
                        }
                        placeholder="Yearly price"
                        required
                    />
                </div>

                <input
                    className={fieldClass}
                    type="number"
                    min="0"
                    max="99999"
                    value={
                        form.data.public_sort_order
                    }
                    onChange={(e) =>
                        form.setData(
                            'public_sort_order',
                            e.target.value
                        )
                    }
                    placeholder="Website display order"
                    required
                />

                <input
                    className={fieldClass}
                    value={form.data.cta_text}
                    onChange={(e) =>
                        form.setData(
                            'cta_text',
                            e.target.value
                        )
                    }
                    placeholder="Website button text"
                />

                <textarea
                    className={`${fieldClass} min-h-28 md:col-span-2 xl:col-span-4`}
                    value={form.data.description}
                    onChange={(e) =>
                        form.setData(
                            'description',
                            e.target.value
                        )
                    }
                    placeholder="Short public description shown on your pricing cards"
                />

                <textarea
                    className={`${fieldClass} min-h-36 xl:col-span-2`}
                    value={
                        form.data.features_text
                    }
                    onChange={(e) =>
                        form.setData(
                            'features_text',
                            e.target.value
                        )
                    }
                    placeholder={
                        'Features — one per line\nUnlimited contacts\nPriority support'
                    }
                />

                <textarea
                    className={`${fieldClass} min-h-36 font-mono text-xs xl:col-span-2`}
                    value={form.data.limits_json}
                    onChange={(e) =>
                        form.setData(
                            'limits_json',
                            e.target.value
                        )
                    }
                    placeholder='{"whatsapp_messages_per_month": 10000}'
                />
            </div>

            <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                <Toggle
                    checked={form.data.is_active}
                    onChange={(value) =>
                        form.setData(
                            'is_active',
                            value
                        )
                    }
                    label="Available for clients"
                    hint="Can be allocated to your clients."
                    icon={ShieldCheck}
                />

                <Toggle
                    checked={
                        form.data.show_on_website
                    }
                    onChange={(value) =>
                        form.setData(
                            'show_on_website',
                            value
                        )
                    }
                    label="Show on website"
                    hint="Publish this plan on your own white-label website only."
                    icon={Globe2}
                />

                <Toggle
                    checked={form.data.is_featured}
                    onChange={(value) =>
                        form.setData(
                            'is_featured',
                            value
                        )
                    }
                    label="Featured plan"
                    hint="Highlights this plan in your public pricing cards."
                    icon={Star}
                />

                <div className="rounded-[11px] border border-[#34363a] bg-[#17181a] p-3">
                    <label className="flex items-center gap-2 text-sm text-[#bfc2c7]">
                        <input
                            type="checkbox"
                            checked={
                                form.data.export_enabled
                            }
                            onChange={(e) =>
                                form.setData(
                                    'export_enabled',
                                    e.target.checked
                                )
                            }
                        />
                        Export enabled
                    </label>

                    <label className="mt-3 flex items-center gap-2 text-sm text-[#bfc2c7]">
                        <input
                            type="checkbox"
                            checked={
                                form.data.custom_domain_enabled
                            }
                            onChange={(e) =>
                                form.setData(
                                    'custom_domain_enabled',
                                    e.target.checked
                                )
                            }
                        />
                        Custom domain
                    </label>
                </div>
            </div>

            <div className="mt-5 flex flex-wrap gap-3">
                <button
                    disabled={form.processing}
                    className="inline-flex items-center gap-2 rounded-[10px] bg-[#4d7f3a] px-4 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
                >
                    <Save className="h-4 w-4" />
                    Save Plan
                </button>

                <button
                    type="button"
                    onClick={() => {
                        if (
                            confirm(
                                'Delete this plan from your white-label panel? Existing assigned clients will remain safe.'
                            )
                        ) {
                            router.delete(
                                route(
                                    'white-label.admin.plans.destroy',
                                    plan.id
                                ),
                                {
                                    preserveScroll: true,
                                }
                            );
                        }
                    }}
                    className="inline-flex items-center gap-2 rounded-[10px] border border-red-900/70 px-4 py-2.5 text-sm font-semibold text-red-300 hover:bg-red-950/30"
                >
                    <Trash2 className="h-4 w-4" />
                    Delete
                </button>
            </div>
        </form>
    );
}

export default function Plans({
    owner,
    walletSummary,
    plans = [],
}) {
    const create = useForm({
        ...emptyPlan,
        currency_code:
            owner?.currency_code
            || 'INR',
    });

    return (
        <WhiteLabelAdminLayout
            title="Plans"
            owner={owner}
            walletSummary={walletSummary}
        >
            <Head title="White-label Plans" />
            <FlashMessages />

            <div className="mb-7">
                <h2 className="text-[28px] font-bold tracking-tight text-white">
                    Plans
                </h2>
                <p className="mt-1 text-[15px] text-[#999ea5]">
                    Create plans once, publish them on your website and allocate the same plans to your clients.
                </p>
            </div>

            <div className="mb-6 flex items-start gap-3 rounded-[14px] border border-[#33532c] bg-[#152013] p-4 text-sm text-[#aed29c]">
                <ShieldCheck className="mt-0.5 h-5 w-5 shrink-0" />
                <div>
                    Your plans remain tenant-private. "Show on website" publishes
                    them only on your white-label domain. They are never added to
                    the main i-Touch pricing catalog and can never grant another
                    white-label panel.
                </div>
            </div>

            <form
                onSubmit={(e) => {
                    e.preventDefault();

                    create.post(
                        route(
                            'white-label.admin.plans.store'
                        ),
                        {
                            preserveScroll: true,
                            onSuccess: () =>
                                create.setData({
                                    ...emptyPlan,
                                    currency_code:
                                        owner?.currency_code
                                        || 'INR',
                                }),
                        }
                    );
                }}
                className={`${cardClass} mb-6`}
            >
                <div className="mb-5 flex items-center gap-2">
                    <div className="grid h-10 w-10 place-items-center rounded-[12px] bg-[#23331f] text-[#80bd64]">
                        <Plus className="h-5 w-5" />
                    </div>

                    <div>
                        <h3 className="font-semibold text-white">
                            Create Plan
                        </h3>

                        <p className="text-xs text-[#82878e]">
                            New plans are website-visible by default and can also be assigned to clients.
                        </p>
                    </div>
                </div>

                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                    <input
                        className={fieldClass}
                        value={create.data.name}
                        onChange={(e) =>
                            create.setData(
                                'name',
                                e.target.value
                            )
                        }
                        placeholder="Plan name"
                        required
                    />

                    <input
                        className={fieldClass}
                        value={create.data.slug}
                        onChange={(e) =>
                            create.setData(
                                'slug',
                                e.target.value
                            )
                        }
                        placeholder="Slug (optional)"
                    />

                    <input
                        className={fieldClass}
                        value={
                            create.data.currency_code
                        }
                        onChange={(e) =>
                            create.setData(
                                'currency_code',
                                e.target.value.toUpperCase()
                            )
                        }
                        placeholder="Currency"
                        required
                    />

                    <input
                        className={fieldClass}
                        type="number"
                        min="0"
                        max="3650"
                        value={
                            create.data.trial_days
                        }
                        onChange={(e) =>
                            create.setData(
                                'trial_days',
                                e.target.value
                            )
                        }
                        placeholder="Trial days"
                        required
                    />

                    <div className="grid grid-cols-2 gap-2 xl:col-span-2">
                        <input
                            className={fieldClass}
                            type="number"
                            min="0"
                            step="0.01"
                            value={
                                create.data.monthly_price
                            }
                            onChange={(e) =>
                                create.setData(
                                    'monthly_price',
                                    e.target.value
                                )
                            }
                            placeholder="Monthly price"
                            required
                        />

                        <input
                            className={fieldClass}
                            type="number"
                            min="0"
                            step="0.01"
                            value={
                                create.data.yearly_price
                            }
                            onChange={(e) =>
                                create.setData(
                                    'yearly_price',
                                    e.target.value
                                )
                            }
                            placeholder="Yearly price"
                            required
                        />
                    </div>

                    <input
                        className={fieldClass}
                        type="number"
                        min="0"
                        max="99999"
                        value={
                            create.data.public_sort_order
                        }
                        onChange={(e) =>
                            create.setData(
                                'public_sort_order',
                                e.target.value
                            )
                        }
                        placeholder="Website order"
                        required
                    />

                    <input
                        className={fieldClass}
                        value={create.data.cta_text}
                        onChange={(e) =>
                            create.setData(
                                'cta_text',
                                e.target.value
                            )
                        }
                        placeholder="Button text"
                    />

                    <textarea
                        className={`${fieldClass} min-h-28 md:col-span-2 xl:col-span-4`}
                        value={create.data.description}
                        onChange={(e) =>
                            create.setData(
                                'description',
                                e.target.value
                            )
                        }
                        placeholder="Short public plan description"
                    />

                    <textarea
                        className={`${fieldClass} min-h-32 xl:col-span-2`}
                        value={
                            create.data.features_text
                        }
                        onChange={(e) =>
                            create.setData(
                                'features_text',
                                e.target.value
                            )
                        }
                        placeholder="Features — one per line"
                    />

                    <textarea
                        className={`${fieldClass} min-h-32 font-mono text-xs xl:col-span-2`}
                        value={
                            create.data.limits_json
                        }
                        onChange={(e) =>
                            create.setData(
                                'limits_json',
                                e.target.value
                            )
                        }
                        placeholder='{"whatsapp_messages_per_month": 10000}'
                    />
                </div>

                <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                    <Toggle
                        checked={
                            create.data.is_active
                        }
                        onChange={(value) =>
                            create.setData(
                                'is_active',
                                value
                            )
                        }
                        label="Available for clients"
                        hint="Can be allocated immediately."
                        icon={ShieldCheck}
                    />

                    <Toggle
                        checked={
                            create.data.show_on_website
                        }
                        onChange={(value) =>
                            create.setData(
                                'show_on_website',
                                value
                            )
                        }
                        label="Show on website"
                        hint="Public on your domain only."
                        icon={Globe2}
                    />

                    <Toggle
                        checked={
                            create.data.is_featured
                        }
                        onChange={(value) =>
                            create.setData(
                                'is_featured',
                                value
                            )
                        }
                        label="Featured plan"
                        hint="Adds public highlight styling."
                        icon={Star}
                    />

                    <div className="rounded-[11px] border border-[#34363a] bg-[#17181a] p-3">
                        <label className="flex items-center gap-2 text-sm text-[#c2c5c9]">
                            <input
                                type="checkbox"
                                checked={
                                    create.data.export_enabled
                                }
                                onChange={(e) =>
                                    create.setData(
                                        'export_enabled',
                                        e.target.checked
                                    )
                                }
                            />
                            Export enabled
                        </label>

                        <label className="mt-3 flex items-center gap-2 text-sm text-[#c2c5c9]">
                            <input
                                type="checkbox"
                                checked={
                                    create.data.custom_domain_enabled
                                }
                                onChange={(e) =>
                                    create.setData(
                                        'custom_domain_enabled',
                                        e.target.checked
                                    )
                                }
                            />
                            Custom domain
                        </label>
                    </div>
                </div>

                <button
                    disabled={create.processing}
                    className="mt-5 inline-flex items-center gap-2 rounded-[10px] bg-[#4d7f3a] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
                >
                    <Boxes className="h-4 w-4" />
                    {create.processing
                        ? 'Creating…'
                        : 'Create Plan'}
                </button>
            </form>

            <div className="space-y-5">
                {plans.map((plan) => (
                    <PlanEditor
                        key={plan.id}
                        plan={plan}
                        currency={
                            owner?.currency_code
                        }
                    />
                ))}

                {!plans.length && (
                    <div className={`${cardClass} py-14 text-center`}>
                        <Boxes className="mx-auto h-9 w-9 text-[#62676d]" />

                        <div className="mt-3 font-semibold text-white">
                            No white-label plans yet
                        </div>

                        <div className="mt-1 text-sm text-[#7d8289]">
                            Create the first plan above.
                        </div>
                    </div>
                )}
            </div>
        </WhiteLabelAdminLayout>
    );
}
