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

type TenantDetailBootstrap = {
    endpoint: string;
    syncEndpoint: string;
    csrfToken: string;
};

type TenantDetail = {
    id: string;
    companyName: string;
    status: string;
    plan: string;
    trialEndsAt: string | null;
    timezone: string;
    currencyCode: string;
    usersCount: number;
    subscriptions: Array<{ id: string; status: string; startsAt: string | null; trialEndsAt: string | null; endsAt: string | null }>;
    channels: Array<{ id: string; type: string; status: string }>;
    paymentProviders: Array<{ id: string; providerKey: string; enabled: boolean }>;
};

export function AdminTenantDetailWorkspace({ bootstrap }: { bootstrap: TenantDetailBootstrap }) {
    const [detail, setDetail] = useState<TenantDetail | null>(null);
    const [syncing, setSyncing] = useState(false);

    async function load() {
        const response = await fetch(bootstrap.endpoint, {
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
        });
        const json = await response.json();
        setDetail(json.data);
    }

    useEffect(() => {
        void load();
    }, [bootstrap.endpoint]);

    async function syncLifecycle() {
        setSyncing(true);
        await fetch(bootstrap.syncEndpoint, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
        });
        await load();
        setSyncing(false);
    }

    if (!detail) {
        return <div className="rounded-[30px] border border-slate-200/80 bg-white p-10 text-sm text-slate-500 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">Loading tenant detail...</div>;
    }

    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)]">
                <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                    <div>
                        <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Tenant detail</p>
                        <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">{detail.companyName}</h2>
                        <p className="mt-3 text-sm leading-7 text-slate-600">
                            Status: {detail.status} · Plan: {detail.plan} · Trial ends: {detail.trialEndsAt ?? 'N/A'}
                        </p>
                    </div>

                    <button
                        type="button"
                        onClick={syncLifecycle}
                        disabled={syncing}
                        className="rounded-2xl bg-slate-950 px-5 py-3 text-sm font-semibold text-white hover:bg-slate-800 disabled:bg-slate-400"
                    >
                        {syncing ? 'Syncing...' : 'Sync lifecycle'}
                    </button>
                </div>
            </section>

            <div className="grid gap-6 xl:grid-cols-3">
                <div className="rounded-[28px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <h3 className="text-lg font-semibold text-slate-950">Workspace</h3>
                    <p className="mt-3 text-sm text-slate-600">Timezone: {detail.timezone}</p>
                    <p className="mt-2 text-sm text-slate-600">Currency: {detail.currencyCode}</p>
                    <p className="mt-2 text-sm text-slate-600">Users: {detail.usersCount}</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)]">
                    <h3 className="text-lg font-semibold text-slate-950">Subscriptions</h3>
                    <div className="mt-4 space-y-3">
                        {detail.subscriptions.map((subscription) => (
                            <div key={subscription.id} className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                                <p className="font-semibold text-slate-900">{subscription.status}</p>
                                <p className="mt-1">Start: {subscription.startsAt ?? 'N/A'}</p>
                                <p className="mt-1">Trial End: {subscription.trialEndsAt ?? 'N/A'}</p>
                            </div>
                        ))}
                    </div>
                </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)]">
                    <h3 className="text-lg font-semibold text-slate-950">Integrations</h3>
                    <div className="mt-4 space-y-3">
                        {detail.channels.map((channel) => (
                            <div key={channel.id} className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                                <p className="font-semibold text-slate-900">{channel.type}</p>
                                <p className="mt-1">Status: {channel.status}</p>
                            </div>
                        ))}
                        {detail.paymentProviders.map((provider) => (
                            <div key={provider.id} className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                                <p className="font-semibold text-slate-900">{provider.providerKey}</p>
                                <p className="mt-1">Enabled: {provider.enabled ? 'Yes' : 'No'}</p>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
}

export type { TenantDetailBootstrap };
