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

type AdminPlansBootstrap = { endpoint: string; updateBase: string; csrfToken: string };

type PlanRow = {
    id: string;
    name: string;
    slug: string;
    monthlyPrice: string;
    maxUsers: number | null;
    maxBranches: number | null;
    maxChannels: number | null;
    active: boolean;
};

export function AdminPlansWorkspace({ bootstrap }: { bootstrap: AdminPlansBootstrap }) {
    const [rows, setRows] = useState<PlanRow[]>([]);

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

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

    async function updatePlan(row: PlanRow, monthlyPrice: string) {
        const numeric = Number(monthlyPrice.replace(/[^0-9.]/g, ''));

        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({
                monthly_price: Number.isFinite(numeric) ? numeric : 0,
            }),
        });

        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">Plans</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">Name</th>
                            <th className="px-6 py-4 font-semibold">Slug</th>
                            <th className="px-6 py-4 font-semibold">Monthly</th>
                            <th className="px-6 py-4 font-semibold">Max Users</th>
                            <th className="px-6 py-4 font-semibold">Branches</th>
                            <th className="px-6 py-4 font-semibold">Channels</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">{row.name}</td>
                                <td className="px-6 py-5 text-slate-600">{row.slug}</td>
                                <td className="px-6 py-5 text-slate-600">
                                    <input
                                        defaultValue={row.monthlyPrice.replace('$', '')}
                                        onBlur={(event) => updatePlan(row, event.target.value)}
                                        className="w-28 rounded-xl border border-slate-300 px-3 py-2 text-sm text-slate-900"
                                    />
                                </td>
                                <td className="px-6 py-5 text-slate-600">{row.maxUsers ?? 'Unlimited'}</td>
                                <td className="px-6 py-5 text-slate-600">{row.maxBranches ?? 'Unlimited'}</td>
                                <td className="px-6 py-5 text-slate-600">{row.maxChannels ?? 'Unlimited'}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </section>
    );
}

export type { AdminPlansBootstrap };
