import AdminLayout from '@/Layouts/AdminLayout';
import {
    Badge,
    Button,
    Card,
    Pagination,
} from '@/Components/ui';
import {
    Head,
    router,
    useForm,
    usePage,
} from '@inertiajs/react';
import {
    Building2,
    CreditCard,
    Globe2,
    Palette,
    Plus,
    Settings2,
    Store,
    Users,
    WalletCards,
    X,
} from 'lucide-react';
import { useMemo, useState } from 'react';

const field =
    'w-full rounded-soft border border-neutral-300 dark:border-neutral-600 bg-white dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20';

const label =
    'mb-1 block text-xs font-medium text-neutral-600 dark:text-neutral-300';

const tabButton = (active) =>
    [
        'rounded-lg px-3 py-2 text-sm font-medium transition',
        active
            ? 'bg-brand-600 text-white'
            : 'text-neutral-600 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800',
    ].join(' ');

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

    try {
        return new Intl.NumberFormat('en-IN', {
            style: 'currency',
            currency,
            maximumFractionDigits: 6,
        }).format(n);
    } catch {
        return `${currency} ${n}`;
    }
}

export default function ResellerIndex({
    resellers,
    clients = [],
    filters = {},
}) {
    const page = usePage();
    const flash = page.props.flash || {};
    const errors = page.props.errors || {};

    const [search, setSearch] = useState(
        filters.search || ''
    );

    const [createOpen, setCreateOpen] =
        useState(false);

    const [manageOpen, setManageOpen] =
        useState(false);

    const [activeTab, setActiveTab] =
        useState('overview');

    const [activeReseller, setActiveReseller] =
        useState(null);

    const createForm = useForm({
        name: '',
        email: '',
        phone: '',
        status: 'active',
        currency_code: 'INR',
        admin_name: '',
        admin_email: '',
        password: '',
        password_confirmation: '',
    });

    const walletCreditForm = useForm({
        amount: '',
        description: '',
    });

    const creditLimitForm = useForm({
        credit_limit: '',
    });

    const billingForm = useForm({
        marketing_cost: '',
        utility_cost: '',
        authentication_cost: '',
        service_cost: '',

        marketing_sell: '',
        utility_sell: '',
        authentication_sell: '',
        service_sell: '',

        client_activation_charge: '',
    });

    const domainForm = useForm({
        domain: '',
    });

    const brandingForm = useForm({
        brand_name: '',
        primary_color: '#2563eb',
        tagline: '',
        support_email: '',
        support_phone: '',
        login_heading: '',
    });

    const allocationForm = useForm({
        client_id: '',
        amount: '',
    });

    const reclaimForm = useForm({
        client_id: '',
        amount: '',
    });

    const assignForm = useForm({
        client_id: '',
    });

    const assignedClients = useMemo(() => {
        if (!activeReseller) return [];

        return clients.filter(
            (client) =>
                Number(client.reseller_id) ===
                Number(activeReseller.id)
        );
    }, [clients, activeReseller]);

    const assignableClients = useMemo(() => {
        if (!activeReseller) return [];

        return clients.filter(
            (client) =>
                Number(client.reseller_id) !==
                Number(activeReseller.id)
        );
    }, [clients, activeReseller]);

    const refreshActiveReseller = () => {
        if (!activeReseller) return;

        router.reload({
            only: ['resellers', 'clients'],
            preserveScroll: true,
        });
    };

    const openManage = (reseller) => {
        setActiveReseller(reseller);
        setActiveTab('overview');

        walletCreditForm.reset();

        creditLimitForm.setData(
            'credit_limit',
            reseller.wallet?.credit_limit || '0'
        );

        billingForm.setData({
            marketing_cost:
                reseller.rates?.marketing_cost || '',
            utility_cost:
                reseller.rates?.utility_cost || '',
            authentication_cost:
                reseller.rates?.authentication_cost || '',
            service_cost:
                reseller.rates?.service_cost || '',

            marketing_sell:
                reseller.rates?.marketing_sell || '',
            utility_sell:
                reseller.rates?.utility_sell || '',
            authentication_sell:
                reseller.rates?.authentication_sell || '',
            service_sell:
                reseller.rates?.service_sell || '',

            client_activation_charge:
                reseller.rates?.client_activation_charge || '',
        });

        domainForm.setData(
            'domain',
            reseller.primary_domain || ''
        );

        brandingForm.setData({
            brand_name:
                reseller.branding?.brand_name || '',
            primary_color:
                reseller.branding?.primary_color ||
                '#2563eb',
            tagline:
                reseller.branding?.tagline || '',
            support_email:
                reseller.branding?.support_email || '',
            support_phone:
                reseller.branding?.support_phone || '',
            login_heading:
                reseller.branding?.login_heading || '',
        });

        allocationForm.reset();
        reclaimForm.reset();
        assignForm.reset();

        setManageOpen(true);
    };

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

        createForm.post(
            route('admin.resellers.store'),
            {
                preserveScroll: true,
                onSuccess: () => {
                    createForm.reset();

                    createForm.setData(
                        'status',
                        'active'
                    );

                    createForm.setData(
                        'currency_code',
                        'INR'
                    );

                    setCreateOpen(false);
                },
            }
        );
    };

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

        router.get(
            route('admin.resellers.index'),
            {
                search:
                    search.trim() || undefined,
            },
            {
                preserveState: true,
                preserveScroll: true,
            }
        );
    };

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

        if (!activeReseller) return;

        walletCreditForm.post(
            route(
                'admin.resellers.wallet.credit',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: () => {
                    walletCreditForm.reset();
                    refreshActiveReseller();
                },
            }
        );
    };

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

        if (!activeReseller) return;

        creditLimitForm.put(
            route(
                'admin.resellers.wallet.credit-limit',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: refreshActiveReseller,
            }
        );
    };

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

        if (!activeReseller) return;

        billingForm.put(
            route(
                'admin.resellers.billing.update',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: refreshActiveReseller,
            }
        );
    };

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

        if (!activeReseller) return;

        domainForm.put(
            route(
                'admin.resellers.domain.update',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: refreshActiveReseller,
            }
        );
    };

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

        if (!activeReseller) return;

        brandingForm.put(
            route(
                'admin.resellers.branding.update',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: refreshActiveReseller,
            }
        );
    };

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

        if (!activeReseller) return;

        assignForm.post(
            route(
                'admin.resellers.clients.assign',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: () => {
                    assignForm.reset();
                    refreshActiveReseller();
                },
            }
        );
    };

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

        if (!activeReseller) return;

        allocationForm.post(
            route(
                'admin.resellers.clients.allocate-credit',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: () => {
                    allocationForm.reset();
                    refreshActiveReseller();
                },
            }
        );
    };

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

        if (!activeReseller) return;

        reclaimForm.post(
            route(
                'admin.resellers.clients.reclaim-credit',
                {
                    reseller:
                        activeReseller.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: () => {
                    reclaimForm.reset();
                    refreshActiveReseller();
                },
            }
        );
    };

    const unassignClient = (client) => {
        if (
            !window.confirm(
                `Return ${client.name} to direct platform clients?`
            )
        ) {
            return;
        }

        router.delete(
            route(
                'admin.resellers.clients.unassign',
                {
                    client: client.id,
                }
            ),
            {
                preserveScroll: true,
                onSuccess: refreshActiveReseller,
            }
        );
    };

    const chargeActivation = (client) => {
        if (!activeReseller) return;

        if (
            !window.confirm(
                `Apply activation charge for ${client.name}?`
            )
        ) {
            return;
        }

        router.post(
            route(
                'admin.resellers.clients.activation-charge',
                {
                    reseller:
                        activeReseller.id,
                    client:
                        client.id,
                }
            ),
            {},
            {
                preserveScroll: true,
                onSuccess: refreshActiveReseller,
            }
        );
    };

    const rows = resellers?.data || [];
    const links = resellers?.links || [];

    const tabs = [
        {
            key: 'overview',
            label: 'Overview',
            icon: Store,
        },
        {
            key: 'wallet',
            label: 'Wallet',
            icon: WalletCards,
        },
        {
            key: 'clients',
            label: 'Clients',
            icon: Users,
        },
        {
            key: 'rates',
            label: 'Rates',
            icon: CreditCard,
        },
        {
            key: 'activation',
            label: 'Activation',
            icon: Building2,
        },
        {
            key: 'domain',
            label: 'Domain',
            icon: Globe2,
        },
        {
            key: 'branding',
            label: 'Branding',
            icon: Palette,
        },
    ];

    return (
        <AdminLayout title="Resellers">
            <Head title="Resellers · Admin" />

            <div className="space-y-6">
                {flash.success && (
                    <div className="rounded-soft-lg bg-green-50 dark:bg-green-900/30 px-4 py-3 text-sm text-green-800 dark:text-green-200">
                        {flash.success}
                    </div>
                )}

                {flash.error && (
                    <div className="rounded-soft-lg bg-red-50 dark:bg-red-900/30 px-4 py-3 text-sm text-red-800 dark:text-red-200">
                        {flash.error}
                    </div>
                )}

                {Object.keys(errors).length > 0 && (
                    <div className="rounded-soft-lg bg-red-50 dark:bg-red-900/30 px-4 py-3 text-sm text-red-800 dark:text-red-200">
                        {Object.values(errors)[0]}
                    </div>
                )}

                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <h2 className="flex items-center gap-2 text-xl font-semibold text-neutral-900 dark:text-neutral-100">
                            <Store className="h-5 w-5" />
                            Reseller Management
                        </h2>

                        <p className="mt-1 text-sm text-neutral-500 dark:text-neutral-400">
                            Credit pools, client allocation,
                            pricing and white-label settings.
                        </p>
                    </div>

                    <Button
                        onClick={() =>
                            setCreateOpen(
                                (value) => !value
                            )
                        }
                    >
                        <Plus className="h-4 w-4" />
                        Add Reseller
                    </Button>
                </div>

                {createOpen && (
                    <Card>
                        <form
                            onSubmit={submitCreate}
                            className="space-y-5"
                        >
                            <div>
                                <h3 className="font-semibold">
                                    Create Reseller
                                </h3>

                                <p className="mt-1 text-xs text-neutral-500">
                                    Login account is optional.
                                </p>
                            </div>

                            <div className="grid gap-4 md:grid-cols-3">
                                <div>
                                    <label className={label}>
                                        Reseller Name
                                    </label>

                                    <input
                                        className={field}
                                        value={
                                            createForm.data
                                                .name
                                        }
                                        onChange={(e) =>
                                            createForm.setData(
                                                'name',
                                                e.target.value
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div>
                                    <label className={label}>
                                        Business Email
                                    </label>

                                    <input
                                        type="email"
                                        className={field}
                                        value={
                                            createForm.data
                                                .email
                                        }
                                        onChange={(e) =>
                                            createForm.setData(
                                                'email',
                                                e.target.value
                                            )
                                        }
                                    />
                                </div>

                                <div>
                                    <label className={label}>
                                        Phone
                                    </label>

                                    <input
                                        className={field}
                                        value={
                                            createForm.data
                                                .phone
                                        }
                                        onChange={(e) =>
                                            createForm.setData(
                                                'phone',
                                                e.target.value
                                            )
                                        }
                                    />
                                </div>

                                <div>
                                    <label className={label}>
                                        Currency
                                    </label>

                                    <input
                                        className={field}
                                        value={
                                            createForm.data
                                                .currency_code
                                        }
                                        onChange={(e) =>
                                            createForm.setData(
                                                'currency_code',
                                                e.target.value
                                            )
                                        }
                                    />
                                </div>

                                <div>
                                    <label className={label}>
                                        Status
                                    </label>

                                    <select
                                        className={field}
                                        value={
                                            createForm.data
                                                .status
                                        }
                                        onChange={(e) =>
                                            createForm.setData(
                                                'status',
                                                e.target.value
                                            )
                                        }
                                    >
                                        <option value="active">
                                            Active
                                        </option>
                                        <option value="inactive">
                                            Inactive
                                        </option>
                                    </select>
                                </div>
                            </div>

                            <div className="border-t border-neutral-200 pt-4 dark:border-neutral-700">
                                <h4 className="text-sm font-semibold">
                                    Optional Login
                                </h4>
                            </div>

                            <div className="grid gap-4 md:grid-cols-2">
                                <input
                                    className={field}
                                    placeholder="Administrator name"
                                    value={
                                        createForm.data
                                            .admin_name
                                    }
                                    onChange={(e) =>
                                        createForm.setData(
                                            'admin_name',
                                            e.target.value
                                        )
                                    }
                                />

                                <input
                                    type="email"
                                    className={field}
                                    placeholder="Administrator email"
                                    value={
                                        createForm.data
                                            .admin_email
                                    }
                                    onChange={(e) =>
                                        createForm.setData(
                                            'admin_email',
                                            e.target.value
                                        )
                                    }
                                />

                                <input
                                    type="password"
                                    className={field}
                                    placeholder="Password"
                                    value={
                                        createForm.data
                                            .password
                                    }
                                    onChange={(e) =>
                                        createForm.setData(
                                            'password',
                                            e.target.value
                                        )
                                    }
                                />

                                <input
                                    type="password"
                                    className={field}
                                    placeholder="Confirm password"
                                    value={
                                        createForm.data
                                            .password_confirmation
                                    }
                                    onChange={(e) =>
                                        createForm.setData(
                                            'password_confirmation',
                                            e.target.value
                                        )
                                    }
                                />
                            </div>

                            <div className="flex gap-2">
                                <Button
                                    type="submit"
                                    disabled={
                                        createForm.processing
                                    }
                                >
                                    Create Reseller
                                </Button>

                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() =>
                                        setCreateOpen(false)
                                    }
                                >
                                    Cancel
                                </Button>
                            </div>
                        </form>
                    </Card>
                )}

                <form
                    onSubmit={submitSearch}
                    className="flex max-w-md gap-2"
                >
                    <input
                        className={field}
                        value={search}
                        placeholder="Search resellers..."
                        onChange={(e) =>
                            setSearch(e.target.value)
                        }
                    />

                    <Button
                        type="submit"
                        variant="outline"
                    >
                        Search
                    </Button>
                </form>

                <div className="grid gap-4 md:grid-cols-3">
                    <Card>
                        <p className="text-xs text-neutral-500">
                            Total Resellers
                        </p>

                        <p className="mt-1 text-2xl font-semibold">
                            {resellers?.total || 0}
                        </p>
                    </Card>

                    <Card>
                        <p className="text-xs text-neutral-500">
                            Total Clients
                        </p>

                        <p className="mt-1 text-2xl font-semibold">
                            {clients.length}
                        </p>
                    </Card>

                    <Card>
                        <p className="text-xs text-neutral-500">
                            Credit Control
                        </p>

                        <p className="mt-1 font-semibold">
                            Centralized Wallet
                        </p>
                    </Card>
                </div>

                <Card>
                    <div className="overflow-x-auto">
                        <table className="min-w-full text-sm">
                            <thead>
                                <tr className="border-b border-neutral-200 text-left text-neutral-500 dark:border-neutral-700">
                                    <th className="pb-3 pr-4">
                                        Reseller
                                    </th>

                                    <th className="pb-3 pr-4">
                                        Status
                                    </th>

                                    <th className="pb-3 pr-4">
                                        Clients
                                    </th>

                                    <th className="pb-3 pr-4">
                                        Balance
                                    </th>

                                    <th className="pb-3 pr-4">
                                        Credit Line
                                    </th>

                                    <th className="pb-3 pr-4">
                                        Available
                                    </th>

                                    <th className="pb-3 text-right">
                                        Action
                                    </th>
                                </tr>
                            </thead>

                            <tbody>
                                {rows.map((reseller) => (
                                    <tr
                                        key={reseller.id}
                                        className="border-b border-neutral-100 dark:border-neutral-800"
                                    >
                                        <td className="py-4 pr-4">
                                            <div className="font-medium text-neutral-900 dark:text-neutral-100">
                                                {reseller.name}
                                            </div>

                                            <div className="text-xs text-neutral-500">
                                                {reseller.email ||
                                                    'No email'}
                                            </div>

                                            {reseller.primary_domain && (
                                                <div className="mt-1 text-xs text-brand-500">
                                                    {
                                                        reseller.primary_domain
                                                    }
                                                </div>
                                            )}
                                        </td>

                                        <td className="py-4 pr-4">
                                            <Badge
                                                variant={
                                                    reseller.status ===
                                                    'active'
                                                        ? 'success'
                                                        : 'default'
                                                }
                                            >
                                                {reseller.status}
                                            </Badge>
                                        </td>

                                        <td className="py-4 pr-4">
                                            {
                                                reseller.clients_count
                                            }
                                        </td>

                                        <td className="py-4 pr-4">
                                            {money(
                                                reseller.wallet
                                                    ?.balance,
                                                reseller.currency_code
                                            )}
                                        </td>

                                        <td className="py-4 pr-4">
                                            {money(
                                                reseller.wallet
                                                    ?.credit_limit,
                                                reseller.currency_code
                                            )}
                                        </td>

                                        <td className="py-4 pr-4 font-semibold text-green-600 dark:text-green-400">
                                            {money(
                                                reseller.wallet
                                                    ?.available,
                                                reseller.currency_code
                                            )}
                                        </td>

                                        <td className="py-4 text-right">
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    router.get(
                                                        route(
                                                            'admin.resellers.charges',
                                                            {
                                                                reseller: reseller.id,
                                                            }
                                                        )
                                                    )
                                                }
                                                className="inline-flex items-center gap-1.5 rounded-lg border border-neutral-300 px-3 py-1.5 text-xs font-medium hover:bg-neutral-50 dark:border-neutral-700 dark:hover:bg-neutral-800"
                                            >
                                                Charges
                                            </button>

                                            <button
                                                type="button"
                                                onClick={() =>
                                                    openManage(
                                                        reseller
                                                    )
                                                }
                                                className="inline-flex items-center gap-1.5 rounded-lg border border-neutral-300 px-3 py-1.5 text-xs font-medium hover:bg-neutral-50 dark:border-neutral-700 dark:hover:bg-neutral-800"
                                            >
                                                <Settings2 className="h-3.5 w-3.5" />
                                                Manage
                                            </button>
                                        </td>
                                    </tr>
                                ))}

                                {!rows.length && (
                                    <tr>
                                        <td
                                            colSpan="7"
                                            className="py-10 text-center text-neutral-500"
                                        >
                                            No resellers found.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </Card>

                {links.length > 3 && (
                    <Pagination links={links} />
                )}
            </div>

            {manageOpen && activeReseller && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3 backdrop-blur-sm">
                    <div className="flex max-h-[94vh] w-full max-w-6xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl dark:bg-neutral-900">
                        <div className="flex items-center justify-between border-b border-neutral-200 px-5 py-4 dark:border-neutral-800">
                            <div>
                                <h3 className="text-lg font-semibold">
                                    {activeReseller.name}
                                </h3>

                                <p className="text-xs text-neutral-500">
                                    Reseller Settings
                                </p>
                            </div>

                            <button
                                type="button"
                                onClick={() =>
                                    setManageOpen(false)
                                }
                                className="rounded-full p-2 hover:bg-neutral-100 dark:hover:bg-neutral-800"
                            >
                                <X className="h-5 w-5" />
                            </button>
                        </div>

                        <div className="flex flex-wrap gap-1 border-b border-neutral-200 px-4 py-2 dark:border-neutral-800">
                            {tabs.map((tab) => {
                                const Icon = tab.icon;

                                return (
                                    <button
                                        key={tab.key}
                                        type="button"
                                        onClick={() =>
                                            setActiveTab(
                                                tab.key
                                            )
                                        }
                                        className={tabButton(
                                            activeTab ===
                                                tab.key
                                        )}
                                    >
                                        <span className="flex items-center gap-1.5">
                                            <Icon className="h-4 w-4" />
                                            {tab.label}
                                        </span>
                                    </button>
                                );
                            })}
                        </div>

                        <div className="flex-1 overflow-y-auto p-5">
                            {activeTab ===
                                'overview' && (
                                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                                    <Card>
                                        <p className="text-xs text-neutral-500">
                                            Wallet Balance
                                        </p>

                                        <p className="mt-1 text-xl font-semibold">
                                            {money(
                                                activeReseller
                                                    .wallet
                                                    ?.balance,
                                                activeReseller.currency_code
                                            )}
                                        </p>
                                    </Card>

                                    <Card>
                                        <p className="text-xs text-neutral-500">
                                            Available Credit
                                        </p>

                                        <p className="mt-1 text-xl font-semibold text-green-600">
                                            {money(
                                                activeReseller
                                                    .wallet
                                                    ?.available,
                                                activeReseller.currency_code
                                            )}
                                        </p>
                                    </Card>

                                    <Card>
                                        <p className="text-xs text-neutral-500">
                                            Clients
                                        </p>

                                        <p className="mt-1 text-xl font-semibold">
                                            {
                                                activeReseller.clients_count
                                            }
                                        </p>
                                    </Card>

                                    <Card>
                                        <p className="text-xs text-neutral-500">
                                            Domain
                                        </p>

                                        <p className="mt-1 text-sm font-semibold">
                                            {activeReseller.primary_domain ||
                                                'Not configured'}
                                        </p>
                                    </Card>

                                    <Card className="md:col-span-2">
                                        <p className="text-xs text-neutral-500">
                                            Reseller Login
                                        </p>

                                        {activeReseller
                                            .login_users
                                            ?.length ? (
                                            <div className="mt-2 space-y-2">
                                                {activeReseller.login_users.map(
                                                    (
                                                        user
                                                    ) => (
                                                        <div
                                                            key={
                                                                user.id
                                                            }
                                                            className="flex items-center justify-between rounded-lg border border-neutral-200 px-3 py-2 dark:border-neutral-700"
                                                        >
                                                            <div>
                                                                <div className="text-sm font-medium">
                                                                    {
                                                                        user.name
                                                                    }
                                                                </div>

                                                                <div className="text-xs text-neutral-500">
                                                                    {
                                                                        user.email
                                                                    }
                                                                </div>
                                                            </div>

                                                            <Badge
                                                                variant={
                                                                    user.status ===
                                                                    'active'
                                                                        ? 'success'
                                                                        : 'default'
                                                                }
                                                            >
                                                                {
                                                                    user.status
                                                                }
                                                            </Badge>
                                                        </div>
                                                    )
                                                )}
                                            </div>
                                        ) : (
                                            <p className="mt-2 text-sm text-neutral-500">
                                                No reseller login
                                                account yet.
                                            </p>
                                        )}
                                    </Card>
                                </div>
                            )}

                            {activeTab ===
                                'wallet' && (
                                <div className="grid gap-5 lg:grid-cols-2">
                                    <Card>
                                        <h4 className="font-semibold">
                                            Add Credit
                                        </h4>

                                        <p className="mt-1 text-xs text-neutral-500">
                                            Platform grants
                                            credit to this
                                            reseller wallet.
                                        </p>

                                        <form
                                            onSubmit={
                                                submitWalletCredit
                                            }
                                            className="mt-4 space-y-4"
                                        >
                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Amount
                                                </label>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        walletCreditForm
                                                            .data
                                                            .amount
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        walletCreditForm.setData(
                                                            'amount',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                    placeholder="50000"
                                                />
                                            </div>

                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Description
                                                </label>

                                                <textarea
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        walletCreditForm
                                                            .data
                                                            .description
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        walletCreditForm.setData(
                                                            'description',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>

                                            <Button
                                                type="submit"
                                                disabled={
                                                    walletCreditForm.processing
                                                }
                                            >
                                                Add Credit
                                            </Button>
                                        </form>
                                    </Card>

                                    <Card>
                                        <h4 className="font-semibold">
                                            Credit Line
                                        </h4>

                                        <p className="mt-1 text-xs text-neutral-500">
                                            Optional
                                            platform-approved
                                            extra limit.
                                        </p>

                                        <form
                                            onSubmit={
                                                submitCreditLimit
                                            }
                                            className="mt-4 space-y-4"
                                        >
                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Credit Limit
                                                </label>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        creditLimitForm
                                                            .data
                                                            .credit_limit
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        creditLimitForm.setData(
                                                            'credit_limit',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>

                                            <Button
                                                type="submit"
                                                disabled={
                                                    creditLimitForm.processing
                                                }
                                            >
                                                Save Credit Line
                                            </Button>
                                        </form>
                                    </Card>

                                    <Card className="lg:col-span-2">
                                        <div className="grid gap-4 sm:grid-cols-3">
                                            <div>
                                                <p className="text-xs text-neutral-500">
                                                    Balance
                                                </p>

                                                <p className="text-xl font-semibold">
                                                    {money(
                                                        activeReseller
                                                            .wallet
                                                            ?.balance,
                                                        activeReseller.currency_code
                                                    )}
                                                </p>
                                            </div>

                                            <div>
                                                <p className="text-xs text-neutral-500">
                                                    Credit Line
                                                </p>

                                                <p className="text-xl font-semibold">
                                                    {money(
                                                        activeReseller
                                                            .wallet
                                                            ?.credit_limit,
                                                        activeReseller.currency_code
                                                    )}
                                                </p>
                                            </div>

                                            <div>
                                                <p className="text-xs text-neutral-500">
                                                    Total Available
                                                </p>

                                                <p className="text-xl font-semibold text-green-600">
                                                    {money(
                                                        activeReseller
                                                            .wallet
                                                            ?.available,
                                                        activeReseller.currency_code
                                                    )}
                                                </p>
                                            </div>
                                        </div>
                                    </Card>
                                </div>
                            )}

                            {activeTab ===
                                'clients' && (
                                <div className="space-y-5">
                                    <Card>
                                        <h4 className="font-semibold">
                                            Assign Client
                                        </h4>

                                        <form
                                            onSubmit={
                                                submitAssignClient
                                            }
                                            className="mt-4 flex flex-col gap-3 sm:flex-row"
                                        >
                                            <select
                                                className={
                                                    field
                                                }
                                                value={
                                                    assignForm
                                                        .data
                                                        .client_id
                                                }
                                                onChange={(
                                                    e
                                                ) =>
                                                    assignForm.setData(
                                                        'client_id',
                                                        e
                                                            .target
                                                            .value
                                                    )
                                                }
                                            >
                                                <option value="">
                                                    Select client
                                                </option>

                                                {assignableClients.map(
                                                    (
                                                        client
                                                    ) => (
                                                        <option
                                                            key={
                                                                client.id
                                                            }
                                                            value={
                                                                client.id
                                                            }
                                                        >
                                                            {
                                                                client.name
                                                            }
                                                            {client.reseller_name
                                                                ? ` — ${client.reseller_name}`
                                                                : ' — Direct'}
                                                        </option>
                                                    )
                                                )}
                                            </select>

                                            <Button
                                                type="submit"
                                                disabled={
                                                    assignForm.processing
                                                }
                                            >
                                                Assign
                                            </Button>
                                        </form>
                                    </Card>

                                    <div className="grid gap-5 lg:grid-cols-2">
                                        <Card>
                                            <h4 className="font-semibold">
                                                Allocate Credit
                                            </h4>

                                            <form
                                                onSubmit={
                                                    submitAllocation
                                                }
                                                className="mt-4 space-y-3"
                                            >
                                                <select
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        allocationForm
                                                            .data
                                                            .client_id
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        allocationForm.setData(
                                                            'client_id',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                >
                                                    <option value="">
                                                        Select client
                                                    </option>

                                                    {assignedClients.map(
                                                        (
                                                            client
                                                        ) => (
                                                            <option
                                                                key={
                                                                    client.id
                                                                }
                                                                value={
                                                                    client.id
                                                                }
                                                            >
                                                                {
                                                                    client.name
                                                                }
                                                            </option>
                                                        )
                                                    )}
                                                </select>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    placeholder="Amount"
                                                    value={
                                                        allocationForm
                                                            .data
                                                            .amount
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        allocationForm.setData(
                                                            'amount',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />

                                                <Button type="submit">
                                                    Allocate
                                                </Button>
                                            </form>
                                        </Card>

                                        <Card>
                                            <h4 className="font-semibold">
                                                Reclaim Unused
                                                Credit
                                            </h4>

                                            <form
                                                onSubmit={
                                                    submitReclaim
                                                }
                                                className="mt-4 space-y-3"
                                            >
                                                <select
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        reclaimForm
                                                            .data
                                                            .client_id
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        reclaimForm.setData(
                                                            'client_id',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                >
                                                    <option value="">
                                                        Select client
                                                    </option>

                                                    {assignedClients.map(
                                                        (
                                                            client
                                                        ) => (
                                                            <option
                                                                key={
                                                                    client.id
                                                                }
                                                                value={
                                                                    client.id
                                                                }
                                                            >
                                                                {
                                                                    client.name
                                                                }
                                                            </option>
                                                        )
                                                    )}
                                                </select>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    placeholder="Amount"
                                                    value={
                                                        reclaimForm
                                                            .data
                                                            .amount
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        reclaimForm.setData(
                                                            'amount',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />

                                                <Button
                                                    type="submit"
                                                    variant="outline"
                                                >
                                                    Reclaim
                                                </Button>
                                            </form>
                                        </Card>
                                    </div>

                                    <Card>
                                        <div className="overflow-x-auto">
                                            <table className="min-w-full text-sm">
                                                <thead>
                                                    <tr className="border-b text-left text-neutral-500 dark:border-neutral-700">
                                                        <th className="pb-3 pr-4">
                                                            Client
                                                        </th>

                                                        <th className="pb-3 pr-4">
                                                            Wallet
                                                        </th>

                                                        <th className="pb-3 text-right">
                                                            Actions
                                                        </th>
                                                    </tr>
                                                </thead>

                                                <tbody>
                                                    {assignedClients.map(
                                                        (
                                                            client
                                                        ) => (
                                                            <tr
                                                                key={
                                                                    client.id
                                                                }
                                                                className="border-b border-neutral-100 dark:border-neutral-800"
                                                            >
                                                                <td className="py-3 pr-4">
                                                                    <div className="font-medium">
                                                                        {
                                                                            client.name
                                                                        }
                                                                    </div>

                                                                    <div className="text-xs text-neutral-500">
                                                                        {client.email ||
                                                                            '—'}
                                                                    </div>
                                                                </td>

                                                                <td className="py-3 pr-4">
                                                                    {money(
                                                                        client.wallet_balance,
                                                                        activeReseller.currency_code
                                                                    )}
                                                                </td>

                                                                <td className="py-3 text-right">
                                                                    <div className="flex justify-end gap-2">
                                                                        <button
                                                                            type="button"
                                                                            onClick={() =>
                                                                                chargeActivation(
                                                                                    client
                                                                                )
                                                                            }
                                                                            className="rounded-lg border px-2.5 py-1.5 text-xs"
                                                                        >
                                                                            Activation
                                                                            Charge
                                                                        </button>

                                                                        <button
                                                                            type="button"
                                                                            onClick={() =>
                                                                                unassignClient(
                                                                                    client
                                                                                )
                                                                            }
                                                                            className="rounded-lg border border-red-300 px-2.5 py-1.5 text-xs text-red-600"
                                                                        >
                                                                            Unassign
                                                                        </button>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        )
                                                    )}

                                                    {!assignedClients.length && (
                                                        <tr>
                                                            <td
                                                                colSpan="3"
                                                                className="py-8 text-center text-neutral-500"
                                                            >
                                                                No
                                                                clients
                                                                assigned.
                                                            </td>
                                                        </tr>
                                                    )}
                                                </tbody>
                                            </table>
                                        </div>
                                    </Card>
                                </div>
                            )}

                            {activeTab ===
                                'rates' && (
                                <form
                                    onSubmit={
                                        submitBilling
                                    }
                                    className="space-y-5"
                                >
                                    <div className="grid gap-5 lg:grid-cols-2">
                                        <Card>
                                            <h4 className="font-semibold">
                                                Platform Cost to
                                                Reseller
                                            </h4>

                                            <p className="mt-1 text-xs text-neutral-500">
                                                Used for reseller
                                                margin analytics.
                                            </p>

                                            <div className="mt-4 grid gap-4">
                                                {[
                                                    [
                                                        'marketing_cost',
                                                        'Marketing',
                                                    ],
                                                    [
                                                        'utility_cost',
                                                        'Utility',
                                                    ],
                                                    [
                                                        'authentication_cost',
                                                        'Authentication',
                                                    ],
                                                    [
                                                        'service_cost',
                                                        'Service',
                                                    ],
                                                ].map(
                                                    ([
                                                        key,
                                                        title,
                                                    ]) => (
                                                        <div
                                                            key={
                                                                key
                                                            }
                                                        >
                                                            <label
                                                                className={
                                                                    label
                                                                }
                                                            >
                                                                {
                                                                    title
                                                                }
                                                            </label>

                                                            <input
                                                                className={
                                                                    field
                                                                }
                                                                value={
                                                                    billingForm
                                                                        .data[
                                                                        key
                                                                    ]
                                                                }
                                                                onChange={(
                                                                    e
                                                                ) =>
                                                                    billingForm.setData(
                                                                        key,
                                                                        e
                                                                            .target
                                                                            .value
                                                                    )
                                                                }
                                                                placeholder="0.00"
                                                            />
                                                        </div>
                                                    )
                                                )}
                                            </div>
                                        </Card>

                                        <Card>
                                            <h4 className="font-semibold">
                                                Default Client
                                                Selling Rates
                                            </h4>

                                            <p className="mt-1 text-xs text-neutral-500">
                                                Clients inherit
                                                these unless client
                                                override exists.
                                            </p>

                                            <div className="mt-4 grid gap-4">
                                                {[
                                                    [
                                                        'marketing_sell',
                                                        'Marketing',
                                                    ],
                                                    [
                                                        'utility_sell',
                                                        'Utility',
                                                    ],
                                                    [
                                                        'authentication_sell',
                                                        'Authentication',
                                                    ],
                                                    [
                                                        'service_sell',
                                                        'Service',
                                                    ],
                                                ].map(
                                                    ([
                                                        key,
                                                        title,
                                                    ]) => (
                                                        <div
                                                            key={
                                                                key
                                                            }
                                                        >
                                                            <label
                                                                className={
                                                                    label
                                                                }
                                                            >
                                                                {
                                                                    title
                                                                }
                                                            </label>

                                                            <input
                                                                className={
                                                                    field
                                                                }
                                                                value={
                                                                    billingForm
                                                                        .data[
                                                                        key
                                                                    ]
                                                                }
                                                                onChange={(
                                                                    e
                                                                ) =>
                                                                    billingForm.setData(
                                                                        key,
                                                                        e
                                                                            .target
                                                                            .value
                                                                    )
                                                                }
                                                                placeholder="0.00"
                                                            />
                                                        </div>
                                                    )
                                                )}
                                            </div>
                                        </Card>
                                    </div>

                                    <Button
                                        type="submit"
                                        disabled={
                                            billingForm.processing
                                        }
                                    >
                                        Save Rates
                                    </Button>
                                </form>
                            )}

                            {activeTab ===
                                'activation' && (
                                <form
                                    onSubmit={
                                        submitBilling
                                    }
                                    className="max-w-xl"
                                >
                                    <Card>
                                        <h4 className="font-semibold">
                                            Client Activation
                                            Charge
                                        </h4>

                                        <p className="mt-1 text-xs text-neutral-500">
                                            This charge is
                                            deducted from reseller
                                            wallet when activation
                                            is applied.
                                        </p>

                                        <div className="mt-4">
                                            <label
                                                className={
                                                    label
                                                }
                                            >
                                                Activation Amount
                                            </label>

                                            <input
                                                className={
                                                    field
                                                }
                                                value={
                                                    billingForm
                                                        .data
                                                        .client_activation_charge
                                                }
                                                onChange={(e) =>
                                                    billingForm.setData(
                                                        'client_activation_charge',
                                                        e
                                                            .target
                                                            .value
                                                    )
                                                }
                                                placeholder="0.00"
                                            />
                                        </div>

                                        <Button
                                            type="submit"
                                            className="mt-4"
                                        >
                                            Save Activation
                                            Charge
                                        </Button>
                                    </Card>
                                </form>
                            )}

                            {activeTab ===
                                'domain' && (
                                <form
                                    onSubmit={
                                        submitDomain
                                    }
                                    className="max-w-2xl"
                                >
                                    <Card>
                                        <h4 className="font-semibold">
                                            White-label Domain
                                        </h4>

                                        <p className="mt-1 text-xs text-neutral-500">
                                            Example:
                                            panel.example.com
                                        </p>

                                        <div className="mt-4">
                                            <label
                                                className={
                                                    label
                                                }
                                            >
                                                Domain
                                            </label>

                                            <input
                                                className={
                                                    field
                                                }
                                                value={
                                                    domainForm
                                                        .data
                                                        .domain
                                                }
                                                onChange={(e) =>
                                                    domainForm.setData(
                                                        'domain',
                                                        e
                                                            .target
                                                            .value
                                                    )
                                                }
                                            />
                                        </div>

                                        <div className="mt-4 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:bg-amber-900/20 dark:text-amber-300">
                                            Saving domain does
                                            not activate DNS/SSL
                                            automatically yet.
                                            Verification will be
                                            added in domain
                                            routing phase.
                                        </div>

                                        <Button
                                            type="submit"
                                            className="mt-4"
                                        >
                                            Save Domain
                                        </Button>
                                    </Card>
                                </form>
                            )}

                            {activeTab ===
                                'branding' && (
                                <form
                                    onSubmit={
                                        submitBranding
                                    }
                                    className="space-y-5"
                                >
                                    <Card>
                                        <div className="grid gap-4 md:grid-cols-2">
                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Brand Name
                                                </label>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        brandingForm
                                                            .data
                                                            .brand_name
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        brandingForm.setData(
                                                            'brand_name',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>

                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Primary Color
                                                </label>

                                                <div className="flex gap-2">
                                                    <input
                                                        type="color"
                                                        className="h-10 w-14 rounded border"
                                                        value={
                                                            brandingForm
                                                                .data
                                                                .primary_color ||
                                                            '#2563eb'
                                                        }
                                                        onChange={(
                                                            e
                                                        ) =>
                                                            brandingForm.setData(
                                                                'primary_color',
                                                                e
                                                                    .target
                                                                    .value
                                                            )
                                                        }
                                                    />

                                                    <input
                                                        className={
                                                            field
                                                        }
                                                        value={
                                                            brandingForm
                                                                .data
                                                                .primary_color
                                                        }
                                                        onChange={(
                                                            e
                                                        ) =>
                                                            brandingForm.setData(
                                                                'primary_color',
                                                                e
                                                                    .target
                                                                    .value
                                                            )
                                                        }
                                                    />
                                                </div>
                                            </div>

                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Tagline
                                                </label>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        brandingForm
                                                            .data
                                                            .tagline
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        brandingForm.setData(
                                                            'tagline',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>

                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Login Heading
                                                </label>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        brandingForm
                                                            .data
                                                            .login_heading
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        brandingForm.setData(
                                                            'login_heading',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>

                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Support Email
                                                </label>

                                                <input
                                                    type="email"
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        brandingForm
                                                            .data
                                                            .support_email
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        brandingForm.setData(
                                                            'support_email',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>

                                            <div>
                                                <label
                                                    className={
                                                        label
                                                    }
                                                >
                                                    Support Phone
                                                </label>

                                                <input
                                                    className={
                                                        field
                                                    }
                                                    value={
                                                        brandingForm
                                                            .data
                                                            .support_phone
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        brandingForm.setData(
                                                            'support_phone',
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                />
                                            </div>
                                        </div>

                                        <Button
                                            type="submit"
                                            className="mt-5"
                                        >
                                            Save Branding
                                        </Button>
                                    </Card>
                                </form>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </AdminLayout>
    );
}
