import * as React from 'react';
import { useState } from 'react';
import { 
  X, 
  Crown, 
  Save, 
  AlertTriangle, 
  CheckCircle,
  BarChart3,
  Phone,
  MessageSquare,
  Bell,
  Users,
  Shield,
  Building2,
  Settings
} from 'lucide-react';

interface Role {
  id: number;
  name: string;
  description: string;
  level: number;
  permissions: string[];
}

interface Permission {
  id: number;
  name: string;
  description: string;
  resource: string;
  action: string;
}

interface RoleModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (role: Role) => void;
  mode: 'create' | 'edit';
  role?: Role | null;
  permissions?: Permission[];
}

const RoleModal: React.FC<RoleModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  mode,
  role = null,
  permissions = []
}) => {
  // Helper function to get icon for resource
  const getIconForResource = (resource: string) => {
    switch (resource) {
      case 'dashboard': return BarChart3;
      case 'contact': return Phone;
      case 'conversation': return MessageSquare;
      case 'notification': return Bell;
      case 'user': return Users;
      case 'role': return Shield;
      case 'unit': return Building2;
      case 'settings': return Settings;
      default: return Shield;
    }
  };

  // Group permissions by resource dynamically
  const permissionGroups = React.useMemo(() => {
    if (!permissions || permissions.length === 0) {
      return [];
    }
    
    const grouped = permissions.reduce((acc, permission) => {
      const resource = permission.resource;
      if (!acc[resource]) {
        acc[resource] = {
          id: resource,
          name: resource.charAt(0).toUpperCase() + resource.slice(1),
          icon: getIconForResource(resource),
          description: `${resource} management`,
          permissions: []
        };
      }
      acc[resource].permissions.push(permission);
      return acc;
    }, {} as Record<string, any>);
    
    return Object.values(grouped);
  }, [permissions]);

  // Fallback permissions if none provided
  const fallbackPermissionGroups = [
    {
      id: 'dashboard',
      name: 'Dashboard',
      icon: BarChart3,
      description: 'Dashboard and analytics access',
      permissions: [
        { id: 1, name: 'dashboard.view', description: 'View dashboard', resource: 'dashboard', action: 'view' },
        { id: 2, name: 'dashboard.analytics', description: 'View analytics and reports', resource: 'dashboard', action: 'analytics' }
      ]
    },
    {
      id: 'directory',
      name: 'Directory',
      icon: Phone,
      description: 'Contact directory management',
      permissions: [
        { id: 3, name: 'contact.create', description: 'Create contacts', resource: 'contact', action: 'create' },
        { id: 4, name: 'contact.read', description: 'View contacts', resource: 'contact', action: 'read' },
        { id: 5, name: 'contact.update', description: 'Update contacts', resource: 'contact', action: 'update' },
        { id: 6, name: 'contact.delete', description: 'Delete contacts', resource: 'contact', action: 'delete' },
        { id: 7, name: 'contact.export', description: 'Export contact data', resource: 'contact', action: 'export' },
        { id: 8, name: 'contact.import', description: 'Import contact data', resource: 'contact', action: 'import' }
      ]
    },
    {
      id: 'messaging',
      name: 'Messaging',
      icon: MessageSquare,
      description: 'Messaging and communication',
      permissions: [
        { id: 9, name: 'message.create', description: 'Create messages', resource: 'message', action: 'create' },
        { id: 10, name: 'message.read', description: 'Read messages', resource: 'message', action: 'read' },
        { id: 11, name: 'message.update', description: 'Update messages', resource: 'message', action: 'update' },
        { id: 12, name: 'message.delete', description: 'Delete messages', resource: 'message', action: 'delete' },
        { id: 13, name: 'conversation.create', description: 'Create conversations', resource: 'conversation', action: 'create' },
        { id: 14, name: 'conversation.read', description: 'Read conversations', resource: 'conversation', action: 'read' },
        { id: 15, name: 'conversation.update', description: 'Update conversations', resource: 'conversation', action: 'update' },
        { id: 16, name: 'conversation.delete', description: 'Delete conversations', resource: 'conversation', action: 'delete' }
      ]
    },
    {
      id: 'notifications',
      name: 'Notifications',
      icon: Bell,
      description: 'Notification management',
      permissions: [
        { id: 17, name: 'notification.read', description: 'Read notifications', resource: 'notification', action: 'read' },
        { id: 18, name: 'notification.update', description: 'Update notifications', resource: 'notification', action: 'update' },
        { id: 19, name: 'notification.create', description: 'Create notifications', resource: 'notification', action: 'create' },
        { id: 20, name: 'notification.delete', description: 'Delete notifications', resource: 'notification', action: 'delete' }
      ]
    },
    {
      id: 'user-management',
      name: 'User Management',
      icon: Users,
      description: 'User account management',
      permissions: [
        { id: 21, name: 'user.create', description: 'Create new users', resource: 'user', action: 'create' },
        { id: 22, name: 'user.read', description: 'View user information', resource: 'user', action: 'read' },
        { id: 23, name: 'user.update', description: 'Update user information', resource: 'user', action: 'update' },
        { id: 24, name: 'user.delete', description: 'Delete users', resource: 'user', action: 'delete' },
        { id: 25, name: 'user.activate', description: 'Activate/deactivate users', resource: 'user', action: 'activate' }
      ]
    },
    {
      id: 'role-management',
      name: 'Role Management',
      icon: Shield,
      description: 'Role and permission management',
      permissions: [
        { id: 26, name: 'role.create', description: 'Create new roles', resource: 'role', action: 'create' },
        { id: 27, name: 'role.read', description: 'View role information', resource: 'role', action: 'read' },
        { id: 28, name: 'role.update', description: 'Update role information', resource: 'role', action: 'update' },
        { id: 29, name: 'role.delete', description: 'Delete roles', resource: 'role', action: 'delete' },
        { id: 30, name: 'permission.create', description: 'Create permissions', resource: 'permission', action: 'create' },
        { id: 31, name: 'permission.read', description: 'View permissions', resource: 'permission', action: 'read' },
        { id: 32, name: 'permission.update', description: 'Update permissions', resource: 'permission', action: 'update' },
        { id: 33, name: 'permission.delete', description: 'Delete permissions', resource: 'permission', action: 'delete' }
      ]
    },
    {
      id: 'organizational',
      name: 'Organizational',
      icon: Building2,
      description: 'Organizational structure management',
      permissions: [
        { id: 34, name: 'unit.create', description: 'Create units', resource: 'unit', action: 'create' },
        { id: 35, name: 'unit.read', description: 'View units', resource: 'unit', action: 'read' },
        { id: 36, name: 'unit.update', description: 'Update units', resource: 'unit', action: 'update' },
        { id: 37, name: 'unit.delete', description: 'Delete units', resource: 'unit', action: 'delete' },
        { id: 38, name: 'department.create', description: 'Create departments', resource: 'department', action: 'create' },
        { id: 39, name: 'department.read', description: 'View departments', resource: 'department', action: 'read' },
        { id: 40, name: 'department.update', description: 'Update departments', resource: 'department', action: 'update' },
        { id: 41, name: 'department.delete', description: 'Delete departments', resource: 'department', action: 'delete' },
        { id: 42, name: 'rank.create', description: 'Create ranks', resource: 'rank', action: 'create' },
        { id: 43, name: 'rank.read', description: 'View ranks', resource: 'rank', action: 'read' },
        { id: 44, name: 'rank.update', description: 'Update ranks', resource: 'rank', action: 'update' },
        { id: 45, name: 'rank.delete', description: 'Delete ranks', resource: 'rank', action: 'delete' }
      ]
    },
    {
      id: 'system',
      name: 'System Settings',
      icon: Settings,
      description: 'System configuration and settings',
      permissions: [
        { id: 46, name: 'system.manage', description: 'Manage system settings', resource: 'system', action: 'manage' },
        { id: 47, name: 'system.backup', description: 'Create system backups', resource: 'system', action: 'backup' },
        { id: 48, name: 'system.restore', description: 'Restore system data', resource: 'system', action: 'restore' },
        { id: 49, name: 'system.logs', description: 'View system logs', resource: 'system', action: 'logs' },
        { id: 50, name: 'system.maintenance', description: 'System maintenance', resource: 'system', action: 'maintenance' }
      ]
    }
  ];

  // Use dynamic permission groups or fallback
  const activePermissionGroups = permissionGroups.length > 0 ? permissionGroups : fallbackPermissionGroups;
  
  // Flatten all permissions for easy access
  const availablePermissions = activePermissionGroups.flatMap(group => group.permissions);

  const [formData, setFormData] = useState({
    name: role?.name || '',
    description: role?.description || '',
    selectedPermissions: role?.permissions || []
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Update form data when role prop changes (for edit mode)
  React.useEffect(() => {
    if (role) {
      // Use permission names from role.permissions
      const rolePermissionNames = role.permissions || [];
      
      setFormData({
        name: role.name || '',
        description: role.description || '',
        selectedPermissions: rolePermissionNames
      });
    } else {
      setFormData({
        name: '',
        description: '',
        selectedPermissions: []
      });
    }
  }, [role]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handlePermissionToggle = (permissionName: string) => {
    setFormData(prev => ({
      ...prev,
      selectedPermissions: prev.selectedPermissions.includes(permissionName)
        ? prev.selectedPermissions.filter(p => p !== permissionName)
        : [...prev.selectedPermissions, permissionName]
    }));
  };

  const handleSelectAll = () => {
    setFormData(prev => ({
      ...prev,
      selectedPermissions: availablePermissions.map(p => p.name)
    }));
  };

  const handleSelectNone = () => {
    setFormData(prev => ({
      ...prev,
      selectedPermissions: []
    }));
  };

  const handleGroupToggle = (groupPermissions: Permission[]) => {
    const groupPermissionNames = groupPermissions.map(p => p.name);
    const allGroupSelected = groupPermissionNames.every(name => 
      formData.selectedPermissions.includes(name)
    );
    
    if (allGroupSelected) {
      // Remove all permissions from this group
      setFormData(prev => ({
        ...prev,
        selectedPermissions: prev.selectedPermissions.filter(
          name => !groupPermissionNames.includes(name)
        )
      }));
    } else {
      // Add all permissions from this group
      setFormData(prev => ({
        ...prev,
        selectedPermissions: [
          ...prev.selectedPermissions.filter(
            name => !groupPermissionNames.includes(name)
          ),
          ...groupPermissionNames
        ]
      }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      // Validate form data
      if (!formData.name.trim()) {
        throw new Error('Role name is required');
      }
      if (!formData.description.trim()) {
        throw new Error('Role description is required');
      }

      // Get permission IDs from selected permission names
      const selectedPermissionIds = formData.selectedPermissions.map(permissionName => {
        const permission = availablePermissions.find(p => p.name === permissionName);
        return permission ? permission.id : null;
      }).filter(id => id !== null);

      // If no permissions are available, create role without permissions
      if (availablePermissions.length === 0) {
        console.log('⚠️ No permissions available, creating role without permissions');
      }

      const roleData: any = {
        name: formData.name.trim(),
        description: formData.description.trim(),
        level: mode === 'edit' && role ? role.level : 50, // Use existing level for edit, default 50 for new
        permissions: selectedPermissionIds
      };

      // Add role ID for edit mode
      if (mode === 'edit' && role) {
        roleData.id = role.id;
      }

      onSuccess(roleData);
      handleClose();
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    if (!loading) {
      setFormData({
        name: '',
        description: '',
        selectedPermissions: []
      });
      setError(null);
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center">
              <Crown className="h-5 w-5 text-white" />
            </div>
            <h2 className="text-xl font-semibold text-gray-900">
              {mode === 'create' ? 'Add New Role' : 'Edit Role'}
            </h2>
          </div>
          <button
            onClick={handleClose}
            disabled={loading}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors disabled:opacity-50"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

        {/* Content */}
        <form onSubmit={handleSubmit} className="p-6">
          {error && (
            <div className="mb-4 p-3 bg-red-100 border border-red-300 rounded-lg">
              <div className="flex items-center space-x-2">
                <AlertTriangle className="h-4 w-4 text-red-600" />
                <p className="text-red-700 text-sm">{error}</p>
              </div>
            </div>
          )}

          <div className="space-y-4">
            {/* Role Name */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Role Name *
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                required
                disabled={loading}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                placeholder="Enter role name (e.g., Manager, Editor)"
              />
            </div>

            {/* Description */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description *
              </label>
              <textarea
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                required
                disabled={loading}
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 resize-none"
                placeholder="Enter role description"
              />
            </div>

             {/* Permissions Selection */}
             <div>
               <div className="flex items-center justify-between mb-3">
                 <label className="block text-sm font-medium text-gray-700">
                   Permissions *
                 </label>
                 <div className="flex space-x-2">
                   <button
                     type="button"
                     onClick={handleSelectAll}
                     disabled={loading}
                     className="text-xs text-blue-600 hover:text-blue-800 disabled:opacity-50"
                   >
                     Select All
                   </button>
                   <span className="text-gray-300">|</span>
                   <button
                     type="button"
                     onClick={handleSelectNone}
                     disabled={loading}
                     className="text-xs text-gray-600 hover:text-gray-800 disabled:opacity-50"
                   >
                     Select None
                   </button>
                 </div>
               </div>
               
               <div className="border border-gray-300 rounded-lg max-h-80 overflow-y-auto">
                 <div className="p-3 bg-gray-50 border-b border-gray-200">
                   <p className="text-xs text-gray-600">
                     Selected: {formData.selectedPermissions.length} of {availablePermissions.length} permissions
                   </p>
                 </div>
                 
                 <div className="divide-y divide-gray-200">
                   {activePermissionGroups.map((group) => {
                     const groupPermissionNames = group.permissions.map((p: any) => p.name);
                     const selectedInGroup = groupPermissionNames.filter((name: string) => 
                       formData.selectedPermissions.includes(name)
                     ).length;
                     const allGroupSelected = selectedInGroup === group.permissions.length;
                     const someGroupSelected = selectedInGroup > 0;
                     
                     return (
                       <div key={group.id} className="p-4">
                         {/* Group Header */}
                         <div className="flex items-center justify-between mb-3">
                           <div className="flex items-center space-x-3">
                             <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                               <group.icon className="h-4 w-4 text-blue-600" />
                             </div>
                             <div>
                               <h4 className="text-sm font-semibold text-gray-900">{group.name}</h4>
                               <p className="text-xs text-gray-500">{group.description}</p>
                             </div>
                           </div>
                           <div className="flex items-center space-x-2">
                             <span className="text-xs text-gray-500">
                               {selectedInGroup}/{group.permissions.length}
                             </span>
                             <button
                               type="button"
                               onClick={() => handleGroupToggle(group.permissions)}
                               disabled={loading}
                               className={`px-2 py-1 text-xs rounded-md transition-colors disabled:opacity-50 ${
                                 allGroupSelected 
                                   ? 'bg-red-100 text-red-700 hover:bg-red-200' 
                                   : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                               }`}
                             >
                               {allGroupSelected ? 'Deselect All' : 'Select All'}
                             </button>
                           </div>
                         </div>
                         
                         {/* Group Permissions */}
                         <div className="ml-8 space-y-2">
                           {group.permissions.map((permission: any) => (
                             <div
                               key={permission.id}
                               className="p-2 hover:bg-gray-50 rounded-md transition-colors"
                             >
                               <label className="flex items-start space-x-3 cursor-pointer">
                               <input
                                 type="checkbox"
                                 checked={formData.selectedPermissions.includes(permission.name)}
                                 onChange={() => handlePermissionToggle(permission.name)}
                                 disabled={loading}
                                 className="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded disabled:opacity-50"
                                 />
                                 <div className="flex-1 min-w-0">
                                   <div className="flex items-center space-x-2">
                                     <span className="text-sm font-medium text-gray-900">
                                       {permission.name}
                                     </span>
                                     <span className="inline-flex px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
                                       {permission.resource}
                                     </span>
                                     <span className="inline-flex px-2 py-0.5 text-xs font-medium rounded-full bg-green-100 text-green-800">
                                       {permission.action}
                                     </span>
                                   </div>
                                   <p className="text-xs text-gray-500 mt-1">
                                     {permission.description}
                                   </p>
                                 </div>
                               </label>
                             </div>
                           ))}
                         </div>
                       </div>
                     );
                   })}
                 </div>
               </div>
               
               <p className="text-xs text-gray-500 mt-2">
                 Select permissions by module or individually. Use "Select All" buttons to quickly assign entire modules.
               </p>
             </div>

            {/* Selected Permissions Preview */}
            {formData.selectedPermissions.length > 0 && (
              <div className="bg-blue-50 p-3 rounded-lg">
                <p className="text-sm text-blue-800 font-medium mb-2">
                  Selected Permissions ({formData.selectedPermissions.length}):
                </p>
                <div className="flex flex-wrap gap-1">
                  {formData.selectedPermissions.slice(0, 6).map((permission, index) => (
                    <span
                      key={index}
                      className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800"
                    >
                      {permission}
                    </span>
                  ))}
                  {formData.selectedPermissions.length > 6 && (
                    <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-600">
                      +{formData.selectedPermissions.length - 6} more
                    </span>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="flex space-x-3 mt-6 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={handleClose}
              disabled={loading}
              className="flex-1 flex items-center justify-center space-x-2 bg-gray-600 text-white py-3 px-4 rounded-lg hover:bg-gray-700 transition-colors disabled:opacity-50"
            >
              <X className="h-4 w-4" />
              <span>Cancel</span>
            </button>
            
            <button
              type="submit"
              disabled={loading}
              className="flex-1 flex items-center justify-center space-x-2 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {loading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  <span>Processing...</span>
                </>
              ) : (
                <>
                  <Save className="h-4 w-4" />
                  <span>{mode === 'create' ? 'Create Role' : 'Update Role'}</span>
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default RoleModal;
