import AdminLayout from '@/Layouts/AdminLayout';
import {
    Head,
    router,
    useForm,
    usePage,
} from '@inertiajs/react';
import {
    BadgeDollarSign,
    Receipt,
} from 'lucide-react';
import { useState } from 'react';

const field =
    'w-full rounded-xl border border-neutral-300 bg-white px-3 py-2.5 text-sm outline-none focus:border-brand-500 dark:border-neutral-700 dark:bg-neutral-800';

const label =
    'mb-1 block text-xs font-medium text-neutral-500';

const categories = [
    {
        key: 'marketing',
        label: 'Marketing',
    },
    {
        key: 'utility',
        label: 'Utility',
    },
    {
        key: 'authentication',
        label: 'Authentication',
    },
    {
        key: 'service',
        label: 'Service',
    },
];

const charges = [
    {
        key: 'client_activation',
        label: 'Client Activation',
        description:
            'Default charge when a reseller client is activated.',
    },
    {
        key: 'reseller_activation',
        label: 'Reseller Activation',
        description:
            'Default reseller onboarding / activation fee.',
    },
    {
        key: 'user_activation',
        label: 'User Activation',
        description:
            'Default charge for additional activated users.',
    },
    {
        key: 'platform_fee',
        label: 'Platform Fee',
        description:
            'General platform charge. Can be manual or monthly.',
    },
];

export default function PlatformSettings({
    currency,
    rates = {},
    charges: currentCharges = {},
}) {
    const {
        flash = {},
        errors = {},
    } = usePage().props;

    const [currencyInput, setCurrencyInput] =
        useState(currency || 'INR');

    const rateForm = useForm({
        currency: currency,

        cost_marketing:
            rates.cost?.marketing || '',

        cost_utility:
            rates.cost?.utility || '',

        cost_authentication:
            rates.cost?.authentication || '',

        cost_service:
            rates.cost?.service || '',

        sell_marketing:
            rates.sell?.marketing || '',

        sell_utility:
            rates.sell?.utility || '',

        sell_authentication:
            rates.sell?.authentication || '',

        sell_service:
            rates.sell?.service || '',
    });

    const chargeForm = useForm({
        currency,

        client_activation_amount:
            currentCharges
                .client_activation
                ?.amount || '',

        client_activation_mode:
            currentCharges
                .client_activation
                ?.mode || 'one_time',

        reseller_activation_amount:
            currentCharges
                .reseller_activation
                ?.amount || '',

        reseller_activation_mode:
            currentCharges
                .reseller_activation
                ?.mode || 'one_time',

        user_activation_amount:
            currentCharges
                .user_activation
                ?.amount || '',

        user_activation_mode:
            currentCharges
                .user_activation
                ?.mode || 'one_time',

        platform_fee_amount:
            currentCharges
                .platform_fee
                ?.amount || '',

        platform_fee_mode:
            currentCharges
                .platform_fee
                ?.mode || 'manual',
    });

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

        router.get(
            route(
                'admin.platform-billing.index'
            ),
            {
                currency:
                    currencyInput
                        .trim()
                        .toUpperCase(),
            }
        );
    };

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

        rateForm.put(
            route(
                'admin.platform-billing.rates.update'
            ),
            {
                preserveScroll: true,
            }
        );
    };

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

        chargeForm.put(
            route(
                'admin.platform-billing.charges.update'
            ),
            {
                preserveScroll: true,
            }
        );
    };

    return (
        <AdminLayout title="Billing Defaults">
            <Head title="Platform Billing Defaults" />

            <div className="space-y-6">
                <div>
                    <div className="flex items-center gap-2">
                        <BadgeDollarSign className="h-6 w-6 text-brand-500" />

                        <h1 className="text-2xl font-bold">
                            Platform Billing Defaults
                        </h1>
                    </div>

                    <p className="mt-1 text-sm text-neutral-500">
                        Central rate card and default fixed charges.
                    </p>
                </div>

                {flash.success && (
                    <div className="rounded-xl bg-green-50 px-4 py-3 text-sm text-green-700 dark:bg-green-900/20 dark:text-green-300">
                        {flash.success}
                    </div>
                )}

                {Object.keys(errors).length > 0 && (
                    <div className="rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700 dark:bg-red-900/20 dark:text-red-300">
                        {Object.values(errors)[0]}
                    </div>
                )}

                <div className="rounded-2xl bg-white p-5 shadow-sm dark:bg-neutral-900">
                    <form
                        onSubmit={loadCurrency}
                        className="flex max-w-sm gap-2"
                    >
                        <div className="flex-1">
                            <label className={label}>
                                Currency
                            </label>

                            <input
                                className={field}
                                maxLength={10}
                                value={currencyInput}
                                onChange={(e) =>
                                    setCurrencyInput(
                                        e.target.value
                                    )
                                }
                                placeholder="INR"
                            />
                        </div>

                        <button
                            type="submit"
                            className="mt-5 rounded-xl border border-neutral-300 px-4 py-2 text-sm font-medium dark:border-neutral-700"
                        >
                            Load
                        </button>
                    </form>

                    <p className="mt-2 text-xs text-neutral-500">
                        Current rate card: {currency}
                    </p>
                </div>

                <form
                    onSubmit={saveRates}
                    className="rounded-2xl bg-white p-5 shadow-sm dark:bg-neutral-900"
                >
                    <div>
                        <h2 className="font-semibold">
                            WhatsApp Rate Card
                        </h2>

                        <p className="mt-1 text-xs text-neutral-500">
                            Rates support up to 6 decimal places.
                            Blank removes that platform default.
                        </p>
                    </div>

                    <div className="mt-5 overflow-x-auto">
                        <table className="min-w-full text-sm">
                            <thead>
                                <tr className="border-b text-left text-neutral-500 dark:border-neutral-800">
                                    <th className="pb-3 pr-5">
                                        Category
                                    </th>

                                    <th className="pb-3 pr-5">
                                        Platform Cost
                                    </th>

                                    <th className="pb-3">
                                        Default Client Sell
                                    </th>
                                </tr>
                            </thead>

                            <tbody>
                                {categories.map(
                                    (category) => (
                                        <tr
                                            key={category.key}
                                            className="border-b border-neutral-100 dark:border-neutral-800"
                                        >
                                            <td className="py-4 pr-5 font-medium">
                                                {category.label}
                                            </td>

                                            <td className="py-4 pr-5">
                                                <input
                                                    className={`${field} min-w-[150px]`}
                                                    value={
                                                        rateForm
                                                            .data[
                                                            `cost_${category.key}`
                                                        ]
                                                    }
                                                    placeholder="0.000000"
                                                    onChange={(e) =>
                                                        rateForm.setData(
                                                            `cost_${category.key}`,
                                                            e.target.value
                                                        )
                                                    }
                                                />
                                            </td>

                                            <td className="py-4">
                                                <input
                                                    className={`${field} min-w-[150px]`}
                                                    value={
                                                        rateForm
                                                            .data[
                                                            `sell_${category.key}`
                                                        ]
                                                    }
                                                    placeholder="0.000000"
                                                    onChange={(e) =>
                                                        rateForm.setData(
                                                            `sell_${category.key}`,
                                                            e.target.value
                                                        )
                                                    }
                                                />
                                            </td>
                                        </tr>
                                    )
                                )}
                            </tbody>
                        </table>
                    </div>

                    <div className="mt-4 rounded-xl bg-blue-50 px-4 py-3 text-xs text-blue-700 dark:bg-blue-900/20 dark:text-blue-300">
                        Platform Cost is the fallback wholesale cost for reseller margin analytics.
                        Default Client Sell is used only when no reseller/client sell override exists.
                    </div>

                    <button
                        type="submit"
                        disabled={rateForm.processing}
                        className="mt-5 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
                    >
                        Save Rate Card
                    </button>
                </form>

                <form
                    onSubmit={saveCharges}
                    className="rounded-2xl bg-white p-5 shadow-sm dark:bg-neutral-900"
                >
                    <div className="flex items-center gap-2">
                        <Receipt className="h-5 w-5 text-brand-500" />

                        <h2 className="font-semibold">
                            Default Fixed Charges
                        </h2>
                    </div>

                    <p className="mt-1 text-xs text-neutral-500">
                        Individual reseller overrides can replace these defaults.
                    </p>

                    <div className="mt-5 grid gap-4 md:grid-cols-2">
                        {charges.map((charge) => (
                            <div
                                key={charge.key}
                                className="rounded-xl border border-neutral-200 p-4 dark:border-neutral-800"
                            >
                                <h3 className="text-sm font-semibold">
                                    {charge.label}
                                </h3>

                                <p className="mt-1 text-xs text-neutral-500">
                                    {charge.description}
                                </p>

                                <div className="mt-4 grid gap-3 sm:grid-cols-2">
                                    <div>
                                        <label className={label}>
                                            Amount
                                        </label>

                                        <input
                                            className={field}
                                            placeholder="0.00"
                                            value={
                                                chargeForm
                                                    .data[
                                                    `${charge.key}_amount`
                                                ]
                                            }
                                            onChange={(e) =>
                                                chargeForm.setData(
                                                    `${charge.key}_amount`,
                                                    e.target.value
                                                )
                                            }
                                        />
                                    </div>

                                    <div>
                                        <label className={label}>
                                            Charge Mode
                                        </label>

                                        <select
                                            className={field}
                                            value={
                                                chargeForm
                                                    .data[
                                                    `${charge.key}_mode`
                                                ]
                                            }
                                            onChange={(e) =>
                                                chargeForm.setData(
                                                    `${charge.key}_mode`,
                                                    e.target.value
                                                )
                                            }
                                        >
                                            <option value="one_time">
                                                One Time
                                            </option>

                                            <option value="manual">
                                                Manual
                                            </option>

                                            <option value="monthly">
                                                Monthly
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>

                    <button
                        type="submit"
                        disabled={chargeForm.processing}
                        className="mt-5 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
                    >
                        Save Default Charges
                    </button>
                </form>
            </div>
        </AdminLayout>
    );
}
