'use client';

import { registerPage } from '../registry.js';
import { useState, useEffect } from 'react';
import { Card, Table, Button, Badge } from '@zen/core/shared/components';
import { PencilEdit01Icon, Cancel01Icon } from '@zen/core/shared/icons';
import { useToast } from '@zen/core/toast';
import AdminHeader from '../components/AdminHeader.js';
import RoleEditModal from '../components/RoleEditModal.client.js';

const RolesPageClient = ({ canManage }) => {
    const toast = useToast();
    const [roles, setRoles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [editingRoleId, setEditingRoleId] = useState(null);
    const [modalOpen, setModalOpen] = useState(false);

    const openEdit = (roleId) => {
        setEditingRoleId(roleId);
        setModalOpen(true);
    };

    const closeModal = () => {
        setModalOpen(false);
        setEditingRoleId(null);
    };

    const columns = [
        {
            key: 'name',
            label: 'Rôle',
            sortable: false,
            render: (role) => (
                <div className="flex items-center gap-2">
                    <span
                        className="inline-block w-3 h-3 rounded-full flex-shrink-0"
                        style={{ backgroundColor: role.color || '#6b7280' }}
                    />
                    <div>
                        <div className="text-sm font-medium text-neutral-900 dark:text-white">
                            {role.name}
                        </div>
                        {role.description && (
                            <div className="text-xs text-neutral-500 dark:text-gray-400">{role.description}</div>
                        )}
                    </div>
                </div>
            ),
            skeleton: { height: 'h-4', width: '60%' },
        },
        {
            key: 'permission_count',
            label: 'Permissions',
            sortable: false,
            render: (role) => (
                <span className="text-sm text-neutral-600 dark:text-gray-300">{role.permission_count}</span>
            ),
            skeleton: { height: 'h-4', width: '40px' },
        },
        {
            key: 'user_count',
            label: 'Utilisateurs',
            sortable: false,
            render: (role) => (
                <span className="text-sm text-neutral-600 dark:text-gray-300">{role.user_count}</span>
            ),
            skeleton: { height: 'h-4', width: '40px' },
        },
        {
            key: 'is_system',
            label: 'Système',
            sortable: false,
            render: (role) => role.is_system ? <Badge variant="default" size="sm">système</Badge> : null,
            skeleton: { height: 'h-4', width: '60px' },
        },
        ...(canManage ? [{
            key: 'actions',
            label: '',
            sortable: false,
            noWrap: true,
            align: 'right',
            render: (role) => (
                <div className="flex items-center justify-end gap-2">
                    <Button
                        variant="secondary"
                        onClick={() => openEdit(role.id)}
                        icon={PencilEdit01Icon}
                    >
                        Modifier
                    </Button>
                    {!role.is_system && (
                        <Button
                            variant="danger"
                            onClick={() => handleDelete(role)}
                            icon={Cancel01Icon}
                        >
                        </Button>
                    )}
                </div>
            ),
            skeleton: { height: 'h-8', width: '80px', className: 'rounded-lg' },
        }] : []),
    ];

    const fetchRoles = async () => {
        setLoading(true);
        try {
            const response = await fetch('/zen/api/roles', { credentials: 'include' });
            if (!response.ok) throw new Error(`Error: ${response.status}`);
            const data = await response.json();
            setRoles(data.roles);
        } catch (err) {
            toast.error(err.message || 'Impossible de charger les rôles');
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (role) => {
        if (!confirm(`Supprimer le rôle "${role.name}" ?`)) return;
        try {
            const response = await fetch(`/zen/api/roles/${role.id}`, {
                method: 'DELETE',
                credentials: 'include',
            });
            const data = await response.json();
            if (!response.ok) {
                toast.error(data.message || 'Impossible de supprimer ce rôle');
                return;
            }
            toast.success('Rôle supprimé');
            fetchRoles();
        } catch {
            toast.error('Impossible de supprimer ce rôle');
        }
    };

    useEffect(() => {
        fetchRoles();
    }, []);

    return (
        <>
            <Card variant="default" padding="none">
                <Table
                    columns={columns}
                    data={roles}
                    loading={loading}
                    emptyMessage="Aucun rôle trouvé"
                    emptyDescription="Créez un rôle pour commencer"
                />
            </Card>

            <RoleEditModal
                roleId={editingRoleId}
                isOpen={modalOpen}
                onClose={closeModal}
                onSaved={fetchRoles}
            />
        </>
    );
};

const RolesPage = ({ user }) => {
    const canManage = user?.permissions?.includes('roles.manage');
    return (
        <div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
            <RolesPageHeader canManage={canManage} />
            <RolesPageClient canManage={canManage} />
        </div>
    );
};

const RolesPageHeader = ({ canManage }) => {
    const [modalOpen, setModalOpen] = useState(false);

    return (
        <>
            <AdminHeader
                title="Rôles"
                description="Gérez les rôles et leurs permissions"
                action={canManage && (
                    <Button variant="primary" onClick={() => setModalOpen(true)}>
                        Nouveau rôle
                    </Button>
                )}
            />
            {canManage && (
                <RoleEditModal
                    roleId="new"
                    isOpen={modalOpen}
                    onClose={() => setModalOpen(false)}
                />
            )}
        </>
    );
};

export default RolesPage;

registerPage({ slug: 'roles', title: 'Rôles', Component: RolesPage });
