'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Card, Table, Button, Badge } from '@zen/core/shared/components';
import { PencilEdit01Icon, Cancel01Icon } from '@zen/core/shared/icons';
import { useToast } from '@zen/core/toast';

const RolesPageClient = () => {
  const router = useRouter();
  const toast = useToast();
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(true);

  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>
          {role.is_system && (
            <Badge variant="default" size="sm">Système</Badge>
          )}
        </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: 'actions',
      label: '',
      sortable: false,
      noWrap: true,
      render: (role) => (
        <div className="flex items-center gap-2">
          <Button
            variant="secondary"
            size="sm"
            onClick={() => router.push(`/admin/roles/edit/${role.id}`)}
            icon={<PencilEdit01Icon className="w-4 h-4" />}
          >
            Modifier
          </Button>
          {!role.is_system && (
            <Button
              variant="danger"
              size="sm"
              onClick={() => handleDelete(role)}
              icon={<Cancel01Icon className="w-4 h-4" />}
            >
              Supprimer
            </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 (err) {
      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>
  );
};

const RolesPage = () => {
  const router = useRouter();

  return (
    <div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg sm:text-xl font-semibold text-neutral-900 dark:text-white">Rôles</h1>
          <p className="mt-1 text-xs text-neutral-400">Gérez les rôles et leurs permissions</p>
        </div>
        <Button
          variant="primary"
          size="sm"
          onClick={() => router.push('/admin/roles/new')}
        >
          Nouveau rôle
        </Button>
      </div>
      <RolesPageClient />
    </div>
  );
};

export default RolesPage;
