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

type RoleRow = {
    id: string;
    name: string;
    permissionsCount: number;
    permissions: string[];
};

type RolesSettingsBootstrap = {
    rolesEndpoint: string;
};

export function RolesSettingsWorkspace({ bootstrap }: { bootstrap: RolesSettingsBootstrap }) {
    const [roles, setRoles] = useState<RoleRow[]>([]);

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

        void loadRoles();
    }, [bootstrap.rolesEndpoint]);

    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">Roles</p>
                <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">Role matrix overview</h2>
                <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                    View the seeded workspace roles and permission breadth. This is the current role foundation used by owner, admin, manager, agent, catalog, and finance users.
                </p>
            </section>

            <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                {roles.map((role) => (
                    <div key={role.id} 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-lg font-semibold text-slate-950">{role.name}</p>
                        <p className="mt-3 text-sm text-slate-500">{role.permissionsCount} mapped permissions</p>
                        <div className="mt-4 flex flex-wrap gap-2">
                            {role.permissions.map((permission) => (
                                <span key={permission} className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">
                                    {permission}
                                </span>
                            ))}
                        </div>
                    </div>
                ))}
            </section>
        </div>
    );
}

export type { RolesSettingsBootstrap };
