import { useState, useEffect, useRef } from 'react';
import { getRoles, deleteRole, updateRole } from '../services/roleService';
import type { Role } from '../types/role';
import { Button } from '@/components/ui/button';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
// CRITICAL FIX: Utiliser le wrapper lazy pour éviter les collisions de noms de variables
import toast from '@/utils/toast';
import { Shield, Edit, Trash2, UserPlus } from 'lucide-react';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';
import { CreateRoleModal } from '../components/CreateRoleModal';
import { EditRoleModal } from '../components/EditRoleModal';
import { AssignRoleModal } from '../components/AssignRoleModal';
import { Input } from '@/components/ui/input';

// FE-PAGE-011: Complete Roles page implementation

export function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [queryError, setQueryError] = useState<Error | null>(null);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const lastMutationRef = useRef<(() => Promise<void>) | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isAssignModalOpen, setIsAssignModalOpen] = useState(false);
  const [assignUserId, setAssignUserId] = useState<string>('');
  const [assignUserName, setAssignUserName] = useState<string>('');

  const loadRoles = async () => {
    try {
      setIsLoading(true);
      setQueryError(null);
      const loadedRoles = await getRoles();
      setRoles(loadedRoles);
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to load roles';
      setQueryError(new Error(errorMessage));
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleToggleActive = async (role: Role) => {
    // Action 3.4.1.3: Store mutation for retry
    const performMutation = async () => {
      await updateRole(role.id, { is_active: !role.is_active });
      toast.success(
        `Role ${!role.is_active ? 'activated' : 'deactivated'} successfully`,
      );
      loadRoles();
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setMutationError(null);

    try {
      await performMutation();
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to update role';
      setMutationError(new Error(errorMessage));
    }
  };

  const handleDeleteClick = async (role: Role) => {
    if (role.is_system) {
      setMutationError(new Error('Cannot delete system roles'));
      return;
    }

    // Action 3.4.1.3: Store mutation for retry
    const performMutation = async () => {
      await deleteRole(role.id);
      toast.success('Role deleted successfully');
      loadRoles();
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setMutationError(null);

    try {
      await performMutation();
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to delete role';
      setMutationError(new Error(errorMessage));
    }
  };

  // Action 3.4.1.3: Retry handler for failed mutations
  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;

    setRetryCount((prev) => prev + 1);
    try {
      await lastMutationRef.current();
    } catch (error) {
      // Error will be handled by the mutation function
    }
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setIsEditModalOpen(true);
  };

  const handleAssignRole = (userId: string, userName?: string) => {
    setAssignUserId(userId);
    setAssignUserName(userName || '');
    setIsAssignModalOpen(true);
  };

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <LoadingSpinner />
        </div>
      </div>
    );
  }

  if (queryError && roles.length === 0) {
    return (
      <div className="container mx-auto px-4 py-8">
        <ErrorDisplay
          error={queryError}
          variant="card"
          severity="error"
          context={{
            action: 'fetching roles',
            resource: 'roles',
          }}
          onRetry={loadRoles}
        />
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {mutationError && (
        <ErrorDisplay
          error={mutationError}
          variant="banner"
          severity="error"
          context={{
            action: 'updating role',
            resource: 'roles',
          }}
          onRetry={retryCount < 3 ? handleRetry : undefined}
          onDismiss={() => {
            setMutationError(null);
            setRetryCount(0);
            lastMutationRef.current = null;
          }}
        />
      )}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold mb-2">Roles Management</h1>
          <p className="text-muted-foreground">
            Manage user roles and permissions
          </p>
        </div>
        <CreateRoleModal onRoleCreated={loadRoles} />
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Roles
          </CardTitle>
        </CardHeader>
        <CardContent>
          {roles.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-muted-foreground">No roles found</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Display Name</TableHead>
                  <TableHead>Description</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Permissions</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {roles.map((role) => (
                  <TableRow key={role.id}>
                    <TableCell className="font-medium">{role.name}</TableCell>
                    <TableCell>{role.display_name}</TableCell>
                    <TableCell className="max-w-md truncate">
                      {role.description}
                    </TableCell>
                    <TableCell>
                      <Badge variant={role.is_active ? 'success' : 'warning'}>
                        {role.is_active ? 'Active' : 'Inactive'}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {role.is_system ? (
                        <Badge variant="primary">System</Badge>
                      ) : (
                        <Badge variant="default">Custom</Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      {role.permissions?.length || 0} permissions
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleToggleActive(role)}
                          disabled={role.is_system}
                        >
                          {role.is_active ? 'Deactivate' : 'Activate'}
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleEdit(role)}
                          disabled={role.is_system}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteClick(role)}
                          disabled={role.is_system}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* FE-PAGE-011: Assign Role Section */}
      <Card className="mt-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <UserPlus className="h-5 w-5" />
            Assign Role to User
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2">
            <Input
              placeholder="User ID"
              value={assignUserId}
              onChange={(e) => setAssignUserId(e.target.value)}
              className="flex-1"
            />
            <Input
              placeholder="User Name (optional)"
              value={assignUserName}
              onChange={(e) => setAssignUserName(e.target.value)}
              className="flex-1"
            />
            <Button
              onClick={() => handleAssignRole(assignUserId, assignUserName)}
              disabled={!assignUserId}
            >
              <UserPlus className="h-4 w-4 mr-2" />
              Assign Role
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Modals */}
      {editingRole && (
        <EditRoleModal
          role={editingRole}
          open={isEditModalOpen}
          onClose={() => {
            setIsEditModalOpen(false);
            setEditingRole(null);
          }}
          onRoleUpdated={loadRoles}
        />
      )}

      <AssignRoleModal
        userId={assignUserId}
        userName={assignUserName}
        availableRoles={roles.filter((r) => r.is_active)}
        open={isAssignModalOpen}
        onClose={() => {
          setIsAssignModalOpen(false);
          setAssignUserId('');
          setAssignUserName('');
        }}
        onRoleAssigned={() => {
          // Could refresh user roles here if needed
        }}
      />
    </div>
  );
}
