import React, { useState, useEffect } from 'react';
import { 
  Plus, 
  Edit, 
  Trash2, 
  Eye, 
  Search, 
  Filter,
  Crown,
  Shield,
  Users,
  AlertTriangle,
  CheckCircle,
  X,
  RefreshCw
} from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { roleApi, Role, Permission } from '../services/api';
import RoleModal from '../components/UI/RoleModal';

const RoleManagement: React.FC = () => {
  const { user, hasRole, isSuperAdmin } = useAuth();
  const navigate = useNavigate();
  
  // State management
  const [roles, setRoles] = useState<Role[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  
  // Search and filter states
  const [searchQuery, setSearchQuery] = useState('');
  const [levelFilter, setLevelFilter] = useState<string>('all');
  
  // Modal states
  const [roleModal, setRoleModal] = useState<{
    isOpen: boolean;
    mode: 'create' | 'edit';
    role: Role | null;
  }>({
    isOpen: false,
    mode: 'create',
    role: null
  });

  // Access control - only Super Admin and Admin can access
  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    
    if (!hasRole('Admin') && !isSuperAdmin()) {
      navigate('/dashboard');
      return;
    }
  }, [user, hasRole, isSuperAdmin, navigate]);

  // Don't render if user doesn't have access
  if (!user || (!hasRole('Admin') && !isSuperAdmin())) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center p-8 bg-white rounded-lg shadow-lg max-w-md">
          <AlertTriangle className="h-16 w-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Access Denied</h2>
          <p className="text-gray-600 mb-4">
            You don't have permission to access Role Management. This area is restricted to administrators only.
          </p>
          <p className="text-sm text-gray-500">
            Your current role: <span className="font-semibold">{user?.role}</span>
          </p>
        </div>
      </div>
    );
  }

  // Fetch roles data
  const fetchRoles = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await roleApi.getRolesWithPermissions();
      if (response.status === 'success' && response.data) {
        setRoles(response.data.roles);
      } else {
        setError(response.message || 'Failed to fetch roles');
      }
    } catch (error: any) {
      setError(error.message || 'Failed to fetch roles');
    } finally {
      setLoading(false);
    }
  };

  // Fetch permissions data
  const fetchPermissions = async () => {
    try {
      const response = await roleApi.getPermissions();
      if (response.status === 'success' && response.data) {
        setPermissions(response.data.permissions);
      }
    } catch (error: any) {
      console.error('Failed to fetch permissions:', error);
    }
  };

  // Load data on component mount
  useEffect(() => {
    fetchRoles();
    fetchPermissions();
  }, []);

  // Role management functions
  const handleCreateRole = async (roleData: any) => {
    try {
      const response = await roleApi.createRole(roleData);
      if (response.status === 'success') {
        await fetchRoles(); // Refresh roles list
        setMessage({ type: 'success', text: 'Role created successfully!' });
        setTimeout(() => setMessage(null), 3000);
        return true;
      } else {
        setMessage({ type: 'error', text: response.message || 'Failed to create role' });
        setTimeout(() => setMessage(null), 3000);
        return false;
      }
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to create role' });
      setTimeout(() => setMessage(null), 3000);
      return false;
    }
  };

  const handleUpdateRole = async (roleId: number, updatedData: any) => {
    try {
      const response = await roleApi.updateRole(roleId, updatedData);
      if (response.status === 'success') {
        await fetchRoles(); // Refresh roles list
        setMessage({ type: 'success', text: 'Role updated successfully!' });
        setTimeout(() => setMessage(null), 3000);
        return true;
      } else {
        setMessage({ type: 'error', text: response.message || 'Failed to update role' });
        setTimeout(() => setMessage(null), 3000);
        return false;
      }
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to update role' });
      setTimeout(() => setMessage(null), 3000);
      return false;
    }
  };

  const handleDeleteRole = async (roleId: number) => {
    if (window.confirm('Are you sure you want to delete this role? This action cannot be undone.')) {
      try {
        const response = await roleApi.deleteRole(roleId);
        if (response.status === 'success') {
          await fetchRoles(); // Refresh roles list
          setMessage({ type: 'success', text: 'Role deleted successfully!' });
          setTimeout(() => setMessage(null), 3000);
          return true;
        } else {
          setMessage({ type: 'error', text: response.message || 'Failed to delete role' });
          setTimeout(() => setMessage(null), 3000);
          return false;
        }
      } catch (error: any) {
        setMessage({ type: 'error', text: error.message || 'Failed to delete role' });
        setTimeout(() => setMessage(null), 3000);
        return false;
      }
    }
    return false;
  };

  // Modal handlers
  const openRoleModal = (mode: 'create' | 'edit', role?: Role) => {
    setRoleModal({
      isOpen: true,
      mode,
      role: role || null
    });
  };

  const closeRoleModal = () => {
    setRoleModal({
      isOpen: false,
      mode: 'create',
      role: null
    });
  };

  const handleRoleSuccess = async (roleData: any) => {
    if (roleModal.mode === 'create') {
      await handleCreateRole(roleData);
    } else {
      await handleUpdateRole(roleData.id, roleData);
    }
    closeRoleModal();
  };

  // Filter roles based on search and level
  const filteredRoles = roles.filter(role => {
    const matchesSearch = role.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         role.description.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesLevel = levelFilter === 'all' || 
                        (levelFilter === 'high' && role.level >= 80) ||
                        (levelFilter === 'medium' && role.level >= 40 && role.level < 80) ||
                        (levelFilter === 'low' && role.level < 40);
    
    return matchesSearch && matchesLevel;
  });

  // Get role level badge color
  const getLevelBadgeColor = (level: number) => {
    if (level >= 80) return 'bg-red-100 text-red-800';
    if (level >= 40) return 'bg-yellow-100 text-yellow-800';
    return 'bg-green-100 text-green-800';
  };

  // Get role level label
  const getLevelLabel = (level: number) => {
    if (level >= 80) return 'High';
    if (level >= 40) return 'Medium';
    return 'Low';
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-6">
            <div className="flex items-center">
              <Crown className="h-8 w-8 text-blue-600 mr-3" />
              <div>
                <h1 className="text-2xl font-bold text-gray-900">Role Management</h1>
                <p className="text-gray-600">Manage user roles and permissions</p>
              </div>
            </div>
            <div className="flex items-center space-x-3">
              <button
                onClick={fetchRoles}
                className="flex items-center px-3 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <RefreshCw className="h-4 w-4 mr-2" />
                Refresh
              </button>
              <button
                onClick={() => openRoleModal('create')}
                className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                <Plus className="h-4 w-4 mr-2" />
                Add Role
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Message Display */}
        {message && (
          <div className={`mb-6 p-4 rounded-lg flex items-center ${
            message.type === 'success' 
              ? 'bg-green-50 text-green-800 border border-green-200' 
              : 'bg-red-50 text-red-800 border border-red-200'
          }`}>
            {message.type === 'success' ? (
              <CheckCircle className="h-5 w-5 mr-2" />
            ) : (
              <AlertTriangle className="h-5 w-5 mr-2" />
            )}
            {message.text}
            <button
              onClick={() => setMessage(null)}
              className="ml-auto text-gray-400 hover:text-gray-600"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        )}

        {/* Search and Filter */}
        <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search roles by name or description..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
            </div>
            <div className="sm:w-48">
              <select
                value={levelFilter}
                onChange={(e) => setLevelFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="all">All Levels</option>
                <option value="high">High Level (80+)</option>
                <option value="medium">Medium Level (40-79)</option>
                <option value="low">Low Level (1-39)</option>
              </select>
            </div>
          </div>
        </div>

        {/* Roles Table */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="flex items-center space-x-2">
                <RefreshCw className="h-5 w-5 animate-spin text-blue-600" />
                <span className="text-gray-600">Loading roles...</span>
              </div>
            </div>
          ) : error ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <AlertTriangle className="h-12 w-12 text-red-500 mx-auto mb-4" />
                <p className="text-red-600 mb-4">{error}</p>
                <button
                  onClick={fetchRoles}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  Try Again
                </button>
              </div>
            </div>
          ) : filteredRoles.length === 0 ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <Shield className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-600 mb-4">
                  {searchQuery || levelFilter !== 'all' 
                    ? 'No roles match your search criteria' 
                    : 'No roles found'}
                </p>
                {!searchQuery && levelFilter === 'all' && (
                  <button
                    onClick={() => openRoleModal('create')}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    Create First Role
                  </button>
                )}
              </div>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Role Name
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Description
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Level
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Permissions
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {filteredRoles.map((role) => (
                    <tr key={role.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="flex items-center">
                          <div className="flex-shrink-0 h-8 w-8">
                            <div className="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center">
                              <Crown className="h-4 w-4 text-blue-600" />
                            </div>
                          </div>
                          <div className="ml-3">
                            <div className="text-sm font-medium text-gray-900">{role.name}</div>
                            <div className="text-sm text-gray-500">ID: {role.id}</div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm text-gray-900 max-w-xs truncate">
                          {role.description}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getLevelBadgeColor(role.level)}`}>
                          {getLevelLabel(role.level)} ({role.level})
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <div className="space-y-1">
                          {(() => {
                            if (!role.permissions) {
                              return <span className="text-sm text-gray-400 italic">No permissions data</span>;
                            }
                            
                            if (role.permissions.length === 0) {
                              return <span className="text-sm text-gray-400 italic">No permissions assigned</span>;
                            }
                            
                            if (role.permissions.includes('all')) {
                              return (
                                <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">
                                  All Permissions
                                </span>
                              );
                            }
                            
                            return (
                              <div className="flex flex-wrap gap-1">
                                {role.permissions.slice(0, 3).map((permission: string, index: number) => (
                                  <span
                                    key={index}
                                    className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800"
                                  >
                                    {permission}
                                  </span>
                                ))}
                                {role.permissions.length > 3 && (
                                  <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-600">
                                    +{role.permissions.length - 3} more
                                  </span>
                                )}
                              </div>
                            );
                          })()}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <div className="flex space-x-2">
                          <button
                            onClick={() => openRoleModal('edit', role)}
                            className="text-blue-600 hover:text-blue-900 flex items-center"
                          >
                            <Edit className="h-4 w-4 mr-1" />
                            Edit
                          </button>
                          <button
                            onClick={() => handleDeleteRole(role.id)}
                            disabled={role.level >= 100} // Cannot delete Super Admin role
                            className="text-red-600 hover:text-red-900 disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
                          >
                            <Trash2 className="h-4 w-4 mr-1" />
                            Delete
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Stats */}
        <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="bg-white rounded-lg shadow-sm p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <Shield className="h-8 w-8 text-blue-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-500">Total Roles</p>
                <p className="text-2xl font-semibold text-gray-900">{roles.length}</p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-lg shadow-sm p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <Users className="h-8 w-8 text-green-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-500">Active Roles</p>
                <p className="text-2xl font-semibold text-gray-900">
                  {roles.filter(role => role.is_active).length}
                </p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-lg shadow-sm p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <Crown className="h-8 w-8 text-yellow-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-500">High Level Roles</p>
                <p className="text-2xl font-semibold text-gray-900">
                  {roles.filter(role => role.level >= 80).length}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Role Modal */}
      <RoleModal
        isOpen={roleModal.isOpen}
        onClose={closeRoleModal}
        onSuccess={handleRoleSuccess}
        mode={roleModal.mode}
        role={roleModal.role}
        permissions={permissions}
      />
    </div>
  );
};

export default RoleManagement;
