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 { Badge } from '@/components/ui/badge';
import toast from '@/utils/toast';
import { Shield, Edit, Trash2, UserPlus, Lock } 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';
import { cn } from '@/lib/utils';

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) {
      setQueryError(new Error(err instanceof Error ? err.message : 'Failed to load roles'));
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleToggleActive = async (role: Role) => {
    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) { setMutationError(new Error(err instanceof Error ? err.message : 'Failed to update role')); }
  };

  const handleDeleteClick = async (role: Role) => {
    if (role.is_system) { setMutationError(new Error('Cannot delete system roles')); return; }
    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) { setMutationError(new Error(err instanceof Error ? err.message : 'Failed to delete role')); }
  };

  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;
    setRetryCount((prev) => prev + 1);
    try { await lastMutationRef.current(); } catch (error) { }
  };

  if (isLoading) return <div className="flex h-[50vh] items-center justify-center"><LoadingSpinner /></div>;

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

  return (
    <div className="container mx-auto px-4 py-8 max-w-6xl pb-24">
      {mutationError && (
        <ErrorDisplay
          error={mutationError}
          variant="banner"
          severity="error"
          onRetry={retryCount < 3 ? handleRetry : undefined}
          onDismiss={() => { setMutationError(null); setRetryCount(0); lastMutationRef.current = null; }}
        />
      )}

      <div className="mb-8 flex items-end justify-between">
        <div>
          <h1 className="text-3xl font-display font-bold text-white mb-2">Access Control</h1>
          <p className="text-muted-foreground font-mono text-xs flex items-center gap-2">
            <Shield className="w-4 h-4 text-primary" /> ROLE & PERMISSION MATRIX
          </p>
        </div>
        <CreateRoleModal onRoleCreated={loadRoles} />
      </div>

      <div className="grid gap-6">
        <Card variant="glass" className="border-white/5 bg-black/40 overflow-hidden">
          <div className="grid grid-cols-12 gap-4 p-4 border-b border-white/5 text-xs font-bold uppercase tracking-wider text-muted-foreground">
            <div className="col-span-3">Role Identity</div>
            <div className="col-span-3">Attributes</div>
            <div className="col-span-2 text-center">Type</div>
            <div className="col-span-2 text-center">Status</div>
            <div className="col-span-2 text-right">Actions</div>
          </div>

          <div className="divide-y divide-white/5">
            {roles.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">No roles initialized.</div>
            ) : roles.map((role) => (
              <div key={role.id} className="grid grid-cols-12 gap-4 p-4 items-center hover:bg-white/5 transition-colors group">
                <div className="col-span-3">
                  <div className="font-bold text-white group-hover:text-primary transition-colors">{role.name}</div>
                  <div className="text-xs text-muted-foreground">{role.display_name}</div>
                </div>
                <div className="col-span-3 text-sm text-muted-foreground truncate" title={role.description}>
                  {role.description}
                </div>
                <div className="col-span-2 text-center">
                  {role.is_system ? (
                    <Badge variant="primary" className="border-primary/50 text-primary bg-primary/10">SYSTEM</Badge>
                  ) : (
                    <Badge variant="secondary" className="border-white/20 text-muted-foreground">CUSTOM</Badge>
                  )}
                </div>
                <div className="col-span-2 text-center">
                  <div className={cn("inline-flex h-2 w-2 rounded-full", role.is_active ? "bg-lime-500 shadow-[0_0_5px_var(--color-lime-500)]" : "bg-red-500")} />
                </div>
                <div className="col-span-2 flex justify-end gap-2 opacity-60 group-hover:opacity-100 transition-opacity">
                  {role.is_system ? <Lock className="w-4 h-4 text-muted-foreground" /> : (
                    <>
                      <Button size="sm" variant="ghost" onClick={() => handleToggleActive(role)}>
                        {role.is_active ? 'Deactivate' : 'Activate'}
                      </Button>
                      <Button size="sm" variant="ghost" onClick={() => { setEditingRole(role); setIsEditModalOpen(true); }}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="ghost" className="text-red-500 hover:bg-red-500/10" onClick={() => handleDeleteClick(role)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Assign Role Glass Card */}
        <Card variant="glass" className="p-6 border-white/5 bg-black/40">
          <h3 className="font-bold text-white mb-4 flex items-center gap-2 text-sm uppercase tracking-widest">
            <UserPlus className="w-4 h-4 text-primary" /> Role Assignment
          </h3>
          <div className="flex gap-4 items-end">
            <div className="flex-1 space-y-2">
              <label className="text-xs text-muted-foreground ml-1">User ID</label>
              <Input placeholder="UID-..." value={assignUserId} onChange={(e) => setAssignUserId(e.target.value)} className="bg-black/40 font-mono" />
            </div>
            <div className="flex-1 space-y-2">
              <label className="text-xs text-muted-foreground ml-1">Username (Optional)</label>
              <Input placeholder="@username" value={assignUserName} onChange={(e) => setAssignUserName(e.target.value)} className="bg-black/40" />
            </div>
            <Button onClick={() => { setAssignUserId(assignUserId); setAssignUserName(assignUserName || ''); setIsAssignModalOpen(true); }} disabled={!assignUserId} className="shadow-glow-cyan">
              Assign Access
            </Button>
          </div>
        </Card>
      </div>

      {/* 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={() => { }}
      />
    </div>
  );
}
