import React, { useEffect, useState } from 'react';

type ProviderRow = {
    id: string;
    providerKey: string;
    displayName: string;
    isEnabled: boolean;
    isLiveMode: boolean;
    checkoutBaseUrl: string | null;
    merchantId: string;
    hasMerchantSecret: boolean;
    webhookSecretSet: boolean;
    allowCod: boolean;
    allowManualWhish: boolean;
    manualWhishNumber: string;
};

type BillingBootstrap = {
    portalEndpoint: string;
    upgradeEndpoint: string;
    providersEndpoint: string;
    providerUpdateBase: string;
    csrfToken: string;
};

type PlanRow = {
    id: string;
    name: string;
    slug: string;
    monthlyPrice: string;
    yearlyPrice: string | null;
    maxUsers: number | null;
    maxBranches: number | null;
    maxChannels: number | null;
    maxAutomations: number | null;
    features: string[];
    isCurrent: boolean;
};

type InvoiceRow = {
    id: string;
    invoiceNumber: string;
    planName: string;
    billingCycle: string;
    status: string;
    amount: string;
    currencyCode: string;
    checkoutUrl: string | null;
    paidAt: string | null;
    dueAt: string | null;
    provider: string | null;
};

type PortalData = {
    tenant: {
        companyName: string;
        status: string;
        currencyCode: string;
        trialEndsAt: string | null;
    };
    currentPlan: {
        id: string;
        name: string;
        slug: string;
        monthlyPrice: string;
        maxUsers: number | null;
        maxBranches: number | null;
        maxChannels: number | null;
        maxAutomations: number | null;
    } | null;
    subscription: {
        status: string;
        startsAt: string | null;
        endsAt: string | null;
        endsAtIso: string | null;
        trialEndsAt: string | null;
        isExpired: boolean;
        expiresInDays: number | null;
    } | null;
    plans: PlanRow[];
    invoices: InvoiceRow[];
    providerConfigured: boolean;
};

export function BillingSettingsWorkspace({ bootstrap }: { bootstrap: BillingBootstrap }) {
    const [providers, setProviders] = useState<ProviderRow[]>([]);
    const [secretDrafts, setSecretDrafts] = useState<Record<string, { merchantSecret: string; webhookSecret: string }>>({});
    const [portal, setPortal] = useState<PortalData | null>(null);
    const [loading, setLoading] = useState(true);
    const [processingPlanId, setProcessingPlanId] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);

    async function loadPortal() {
        const response = await fetch(bootstrap.portalEndpoint, {
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
        });
        const json = await response.json();
        setPortal(json.data ?? null);
    }

    async function loadProviders() {
        const response = await fetch(bootstrap.providersEndpoint, {
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
        });
        const json = await response.json();
        setProviders(json.data ?? []);
    }

    useEffect(() => {
        async function loadAll() {
            setLoading(true);
            setError(null);
            try {
                await Promise.all([loadPortal(), loadProviders()]);
            } catch {
                setError('Could not load billing portal data.');
            } finally {
                setLoading(false);
            }
        }

        void loadAll();
    }, [bootstrap.portalEndpoint, bootstrap.providersEndpoint]);

    async function saveProvider(provider: ProviderRow, patch: Partial<ProviderRow> = {}) {
        const next = { ...provider, ...patch };
        const drafts = secretDrafts[provider.id] ?? { merchantSecret: '', webhookSecret: '' };
        await fetch(`${bootstrap.providerUpdateBase}/${provider.providerKey}`, {
            method: 'PATCH',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
            body: JSON.stringify({
                is_enabled: next.isEnabled,
                is_live_mode: next.isLiveMode,
                checkout_base_url: next.checkoutBaseUrl,
                merchant_id: next.merchantId,
                merchant_secret: drafts.merchantSecret || undefined,
                webhook_secret: drafts.webhookSecret || undefined,
                allow_cod: next.allowCod,
                allow_manual_whish: next.allowManualWhish,
                manual_whish_number: next.manualWhishNumber,
            }),
        });
        setSecretDrafts((current) => ({ ...current, [provider.id]: { merchantSecret: '', webhookSecret: '' } }));
        await Promise.all([loadProviders(), loadPortal()]);
    }

    async function upgradePlan(planId: string) {
        setProcessingPlanId(planId);
        setError(null);

        try {
            const response = await fetch(bootstrap.upgradeEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({
                    plan_id: planId,
                    billing_cycle: 'monthly',
                }),
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not create upgrade invoice.');
            }

            await loadPortal();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Could not create upgrade invoice.');
        } finally {
            setProcessingPlanId(null);
        }
    }

    return (
        <div className="space-y-6">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-8 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Billing and subscription</p>
                <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">Package and invoice management</h2>
                <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                    See the current package, compare upgrade plans, create package invoices, and pay invoices using Whish while keeping provider configuration in the same workspace.
                </p>
            </section>

            {error ? (
                <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
                    {error}
                </div>
            ) : null}

            {loading || !portal ? (
                <div className="rounded-2xl border border-slate-200 bg-white px-4 py-4 text-sm text-slate-500">
                    Loading billing portal...
                </div>
            ) : (
                <>
                    <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                        <div className="rounded-[28px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Current package</p>
                            <p className="mt-3 text-2xl font-semibold text-slate-950">{portal.currentPlan?.name ?? 'No package'}</p>
                            <p className="mt-1 text-sm text-slate-500">{portal.currentPlan?.monthlyPrice ?? '-'}/month</p>
                        </div>
                        <div className="rounded-[28px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Subscription status</p>
                            <p className="mt-3 text-2xl font-semibold text-slate-950">{portal.subscription?.status ?? portal.tenant.status}</p>
                            <p className="mt-1 text-sm text-slate-500">Expiry date: {portal.subscription?.endsAt ?? 'Not scheduled'}</p>
                        </div>
                        <div className="rounded-[28px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Trial ends</p>
                            <p className="mt-3 text-2xl font-semibold text-slate-950">{portal.tenant.trialEndsAt ?? 'N/A'}</p>
                            <p className="mt-1 text-sm text-slate-500">{portal.tenant.companyName}</p>
                        </div>
                        <div className="rounded-[28px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Payment provider</p>
                            <p className="mt-3 text-2xl font-semibold text-slate-950">{portal.providerConfigured ? 'Ready' : 'Setup needed'}</p>
                            <p className="mt-1 text-sm text-slate-500">Default currency {portal.tenant.currencyCode}</p>
                        </div>
                    </div>

                    {portal.subscription?.isExpired ? (
                        <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
                            Subscription expired. The workspace is locked until you pay the latest invoice.
                        </div>
                    ) : (
                        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
                            Subscription expires in {portal.subscription?.expiresInDays ?? '-'} day(s).
                        </div>
                    )}

                    <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                        <div className="flex flex-col gap-2">
                            <h3 className="text-xl font-semibold text-slate-950">Available packages</h3>
                            <p className="text-sm text-slate-500">
                                Choose a package to create an upgrade invoice. After payment the workspace package is updated automatically.
                            </p>
                        </div>

                        <div className="mt-5 grid gap-4 xl:grid-cols-3">
                            {portal.plans.map((plan) => (
                                <div key={plan.id} className={`rounded-[28px] border p-5 ${plan.isCurrent ? 'border-emerald-300 bg-emerald-50/50' : 'border-slate-200 bg-white'}`}>
                                    <div className="flex items-start justify-between gap-3">
                                        <div>
                                            <h4 className="text-xl font-semibold text-slate-950">{plan.name}</h4>
                                            <p className="mt-2 text-sm text-slate-500">{plan.monthlyPrice}/month</p>
                                        </div>
                                        {plan.isCurrent ? (
                                            <span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700">Current</span>
                                        ) : null}
                                    </div>

                                    <div className="mt-4 space-y-2 text-sm text-slate-600">
                                        <p>Users: {plan.maxUsers ?? 'Unlimited'}</p>
                                        <p>Branches: {plan.maxBranches ?? 'Unlimited'}</p>
                                        <p>Channels: {plan.maxChannels ?? 'Unlimited'}</p>
                                        <p>Automations: {plan.maxAutomations ?? 'Unlimited'}</p>
                                    </div>

                                    <div className="mt-4 flex flex-wrap gap-2">
                                        {plan.features.map((feature) => (
                                            <span key={feature} className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">
                                                {feature.replaceAll('_', ' ')}
                                            </span>
                                        ))}
                                    </div>

                                    <div className="mt-5">
                                        <button
                                            type="button"
                                            disabled={plan.isCurrent || processingPlanId === plan.id}
                                            onClick={() => upgradePlan(plan.id)}
                                            className="rounded-2xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-300"
                                        >
                                            {processingPlanId === plan.id ? 'Creating invoice...' : plan.isCurrent ? 'Current package' : 'Upgrade to this package'}
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </section>

                    <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                        <div className="flex flex-col gap-2">
                            <h3 className="text-xl font-semibold text-slate-950">Invoice history</h3>
                            <p className="text-sm text-slate-500">
                                Review created package invoices and open checkout links to pay via Whish.
                            </p>
                        </div>

                        <div className="mt-5 space-y-4">
                            {portal.invoices.length === 0 ? (
                                <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-6 text-sm text-slate-500">
                                    No package invoices created yet.
                                </div>
                            ) : (
                                portal.invoices.map((invoice) => (
                                    <div key={invoice.id} className="rounded-[24px] border border-slate-200 bg-slate-50 p-4">
                                        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                                            <div>
                                                <p className="text-sm font-semibold text-slate-950">{invoice.invoiceNumber}</p>
                                                <p className="mt-1 text-sm text-slate-500">
                                                    {invoice.planName} · {invoice.amount} · {invoice.billingCycle}
                                                </p>
                                                <p className="mt-1 text-xs text-slate-500">
                                                    Due {invoice.dueAt ?? 'N/A'} {invoice.paidAt ? `· Paid ${invoice.paidAt}` : ''}
                                                </p>
                                            </div>
                                            <div className="flex flex-wrap items-center gap-3">
                                                <span className={`rounded-full px-3 py-1 text-xs font-semibold ${
                                                    invoice.status === 'paid'
                                                        ? 'bg-emerald-100 text-emerald-700'
                                                        : invoice.status === 'failed'
                                                            ? 'bg-rose-100 text-rose-700'
                                                            : 'bg-amber-100 text-amber-700'
                                                }`}>
                                                    {invoice.status}
                                                </span>
                                                {invoice.checkoutUrl ? (
                                                    <a
                                                        href={invoice.checkoutUrl}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                                                    >
                                                        Pay invoice
                                                    </a>
                                                ) : null}
                                            </div>
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </section>
                </>
            )}

            <div className="space-y-6">
                <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <h3 className="text-xl font-semibold text-slate-950">Payment provider configuration</h3>
                    <p className="mt-2 text-sm text-slate-500">
                        Enable the provider below if you want checkout links for package invoices and customer order payments.
                    </p>
                </section>

                {providers.map((provider) => (
                    <div key={provider.id} className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                            <div>
                                <h3 className="text-xl font-semibold text-slate-950">{provider.displayName}</h3>
                                <p className="mt-2 text-sm text-slate-500">Checkout base URL: {provider.checkoutBaseUrl ?? 'Not configured'}</p>
                            </div>
                            <div className="flex items-center gap-3">
                                <span className={`rounded-full px-3 py-1 text-xs font-semibold ${provider.isEnabled ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-700'}`}>
                                    {provider.isEnabled ? 'Enabled' : 'Disabled'}
                                </span>
                                <button
                                    type="button"
                                    onClick={() => saveProvider(provider, { isEnabled: !provider.isEnabled })}
                                    className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                                >
                                    {provider.isEnabled ? 'Disable' : 'Enable'}
                                </button>
                            </div>
                        </div>

                        {provider.providerKey === 'whish' ? (
                            <div className="mt-5 grid gap-4 md:grid-cols-2">
                                <label className="space-y-1">
                                    <span className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Whish merchant ID</span>
                                    <input
                                        value={provider.merchantId ?? ''}
                                        onChange={(event) => {
                                            const value = event.target.value;
                                            setProviders((current) => current.map((row) => row.id === provider.id ? { ...row, merchantId: value } : row));
                                        }}
                                        className="w-full rounded-2xl border border-slate-300 px-4 py-2.5 text-sm text-slate-800"
                                        placeholder="Required only for API checkout"
                                    />
                                </label>
                                <label className="space-y-1">
                                    <span className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Manual Whish number</span>
                                    <input
                                        value={provider.manualWhishNumber ?? ''}
                                        onChange={(event) => {
                                            const value = event.target.value;
                                            setProviders((current) => current.map((row) => row.id === provider.id ? { ...row, manualWhishNumber: value } : row));
                                        }}
                                        className="w-full rounded-2xl border border-slate-300 px-4 py-2.5 text-sm text-slate-800"
                                        placeholder="e.g. +961xxxxxxxx"
                                    />
                                </label>
                                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
                                    <p>Merchant secret: {provider.hasMerchantSecret ? 'Configured' : 'Not set'}</p>
                                    <p className="mt-1">Webhook secret: {provider.webhookSecretSet ? 'Configured' : 'Not set'}</p>
                                </div>
                                <label className="space-y-1">
                                    <span className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Merchant secret</span>
                                    <input
                                        type="password"
                                        value={secretDrafts[provider.id]?.merchantSecret ?? ''}
                                        onChange={(event) => {
                                            const value = event.target.value;
                                            setSecretDrafts((current) => ({
                                                ...current,
                                                [provider.id]: { ...(current[provider.id] ?? { merchantSecret: '', webhookSecret: '' }), merchantSecret: value },
                                            }));
                                        }}
                                        className="w-full rounded-2xl border border-slate-300 px-4 py-2.5 text-sm text-slate-800"
                                        placeholder="Leave empty to keep current"
                                    />
                                </label>
                                <label className="space-y-1">
                                    <span className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Webhook secret</span>
                                    <input
                                        type="password"
                                        value={secretDrafts[provider.id]?.webhookSecret ?? ''}
                                        onChange={(event) => {
                                            const value = event.target.value;
                                            setSecretDrafts((current) => ({
                                                ...current,
                                                [provider.id]: { ...(current[provider.id] ?? { merchantSecret: '', webhookSecret: '' }), webhookSecret: value },
                                            }));
                                        }}
                                        className="w-full rounded-2xl border border-slate-300 px-4 py-2.5 text-sm text-slate-800"
                                        placeholder="Leave empty to keep current"
                                    />
                                </label>
                                <div className="space-y-2 rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700">
                                    <label className="flex items-center gap-2">
                                        <input
                                            type="checkbox"
                                            checked={provider.allowCod}
                                            onChange={(event) => {
                                                const checked = event.target.checked;
                                                setProviders((current) => current.map((row) => row.id === provider.id ? { ...row, allowCod: checked } : row));
                                            }}
                                        />
                                        Allow Cash on Delivery
                                    </label>
                                    <label className="flex items-center gap-2">
                                        <input
                                            type="checkbox"
                                            checked={provider.allowManualWhish}
                                            onChange={(event) => {
                                                const checked = event.target.checked;
                                                setProviders((current) => current.map((row) => row.id === provider.id ? { ...row, allowManualWhish: checked } : row));
                                            }}
                                        />
                                        Allow Manual Whish transfer
                                    </label>
                                </div>
                                <div className="md:col-span-2">
                                    <button
                                        type="button"
                                        onClick={() => saveProvider(provider)}
                                        className="rounded-2xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800"
                                    >
                                        Save company payment settings
                                    </button>
                                </div>
                            </div>
                        ) : null}
                    </div>
                ))}
            </div>
        </div>
    );
}

export type { BillingBootstrap };
