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

type AdminTenantsBootstrap = { endpoint: string; updateBase: string; plansEndpoint: string; csrfToken: string };

type TenantRow = {
    id: string;
    companyName: string;
    status: string;
    plan: string;
    planId?: string | null;
    usersCount: number;
    trialEndsAt: string | null;
    createdAt: string | null;
};

export function AdminTenantsWorkspace({ bootstrap }: { bootstrap: AdminTenantsBootstrap }) {
    const [rows, setRows] = useState<TenantRow[]>([]);
    const [plans, setPlans] = useState<Array<{ id: string; name: string }>>([]);

    useEffect(() => {
        async function load() {
            const [tenantsResponse, plansResponse] = await Promise.all([
                fetch(bootstrap.endpoint, {
                    credentials: 'same-origin',
                    headers: { Accept: 'application/json' },
                }),
                fetch(bootstrap.plansEndpoint, {
                    credentials: 'same-origin',
                    headers: { Accept: 'application/json' },
                }),
            ]);
            const tenantsJson = await tenantsResponse.json();
            const plansJson = await plansResponse.json();
            setRows(tenantsJson.data ?? []);
            setPlans((plansJson.data ?? []).map((plan: { id: string; name: string }) => ({ id: plan.id, name: plan.name })));
        }

        void load();
    }, [bootstrap.endpoint, bootstrap.plansEndpoint]);

    async function updateTenant(row: TenantRow, patch: Record<string, unknown>) {
        await fetch(`${bootstrap.updateBase}/${row.id}`, {
            method: 'PATCH',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
            body: JSON.stringify(patch),
        });

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

    return (
        <section className="overflow-hidden rounded-[30px] border border-slate-200/80 bg-white shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
            <div className="border-b border-slate-200 px-6 py-5">
                <h3 className="text-xl font-semibold text-slate-950">Tenant list</h3>
            </div>
            <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-slate-200 text-sm">
                    <thead className="bg-slate-50 text-left text-slate-500">
                        <tr>
                            <th className="px-6 py-4 font-semibold">Company</th>
                            <th className="px-6 py-4 font-semibold">Status</th>
                            <th className="px-6 py-4 font-semibold">Plan</th>
                            <th className="px-6 py-4 font-semibold">Users</th>
                            <th className="px-6 py-4 font-semibold">Trial Ends</th>
                            <th className="px-6 py-4 font-semibold">Created</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-200">
                        {rows.map((row) => (
                            <tr key={row.id}>
                                <td className="px-6 py-5 font-semibold text-slate-950">
                                    <a href={`/admin/tenants/${row.id}`} className="text-emerald-700 hover:text-emerald-600">
                                        {row.companyName}
                                    </a>
                                </td>
                                <td className="px-6 py-5 text-slate-600">
                                    <select
                                        value={row.status}
                                        onChange={(event) => updateTenant(row, { status: event.target.value })}
                                        className="rounded-xl border border-slate-300 px-3 py-2 text-sm text-slate-900"
                                    >
                                        {['trial', 'active', 'past_due', 'suspended', 'cancelled'].map((status) => (
                                            <option key={status} value={status}>{status}</option>
                                        ))}
                                    </select>
                                </td>
                                <td className="px-6 py-5 text-slate-600">
                                    <select
                                        value={row.planId ?? ''}
                                        onChange={(event) => updateTenant(row, { plan_id: event.target.value || null })}
                                        className="rounded-xl border border-slate-300 px-3 py-2 text-sm text-slate-900"
                                    >
                                        <option value="">No plan</option>
                                        {plans.map((plan) => (
                                            <option key={plan.id} value={plan.id}>{plan.name}</option>
                                        ))}
                                    </select>
                                </td>
                                <td className="px-6 py-5 text-slate-600">{row.usersCount}</td>
                                <td className="px-6 py-5 text-slate-600">{row.trialEndsAt ?? 'N/A'}</td>
                                <td className="px-6 py-5 text-slate-600">{row.createdAt ?? 'N/A'}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </section>
    );
}

export type { AdminTenantsBootstrap };
