import React, { useState, useEffect } from 'react';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import AdminLayout from '../../components/AdminLayout';
import {
  ArrowLeftIcon,
  CheckIcon,
  XIcon,
  ShieldIcon,
  SaveIcon
} from 'lucide-react';

// Mock data for available permissions
const availablePermissions = [
  // User Management
  { id: 'users:view', name: 'View Users', category: 'User Management', description: 'Can view user profiles and information' },
  { id: 'users:create', name: 'Create Users', category: 'User Management', description: 'Can create new user accounts' },
  { id: 'users:edit', name: 'Edit Users', category: 'User Management', description: 'Can modify user profiles and settings' },
  { id: 'users:delete', name: 'Delete Users', category: 'User Management', description: 'Can delete user accounts' },
  
  // Polls & Surveys
  { id: 'polls:view', name: 'View Polls/Surveys', category: 'Polls & Surveys', description: 'Can view polls and surveys' },
  { id: 'polls:create', name: 'Create Polls/Surveys', category: 'Polls & Surveys', description: 'Can create new polls and surveys' },
  { id: 'polls:edit', name: 'Edit Polls/Surveys', category: 'Polls & Surveys', description: 'Can modify existing polls and surveys' },
  { id: 'polls:delete', name: 'Delete Polls/Surveys', category: 'Polls & Surveys', description: 'Can delete polls and surveys' },
  
  // Complaints Management
  { id: 'complaints:view', name: 'View Complaints', category: 'Complaints', description: 'Can view citizen complaints' },
  { id: 'complaints:edit', name: 'Edit Complaints', category: 'Complaints', description: 'Can modify complaint status and details' },
  { id: 'complaints:delete', name: 'Delete Complaints', category: 'Complaints', description: 'Can delete complaints' },
  { id: 'complaints:assign', name: 'Assign Complaints', category: 'Complaints', description: 'Can assign complaints to staff members' },
  
  // Tenant Management
  { id: 'tenants:view', name: 'View Tenants', category: 'Tenant Management', description: 'Can view tenant information' },
  { id: 'tenants:create', name: 'Create Tenants', category: 'Tenant Management', description: 'Can create new tenants' },
  { id: 'tenants:edit', name: 'Edit Tenants', category: 'Tenant Management', description: 'Can modify tenant settings' },
  { id: 'tenants:delete', name: 'Delete Tenants', category: 'Tenant Management', description: 'Can delete tenants' },
  
  // Reports & Analytics
  { id: 'reports:view', name: 'View Reports', category: 'Reports & Analytics', description: 'Can view system reports' },
  { id: 'reports:export', name: 'Export Reports', category: 'Reports & Analytics', description: 'Can export reports to various formats' },
  { id: 'analytics:view', name: 'View Analytics', category: 'Reports & Analytics', description: 'Can access analytics dashboard' },
  
  // System Settings
  { id: 'settings:view', name: 'View Settings', category: 'System Settings', description: 'Can view system settings' },
  { id: 'settings:edit', name: 'Edit Settings', category: 'System Settings', description: 'Can modify system settings' },
  { id: 'roles:manage', name: 'Manage Roles', category: 'System Settings', description: 'Can create and manage user roles' },
  
  // Dashboard & Overview
  { id: 'dashboard:view', name: 'View Dashboard', category: 'Dashboard', description: 'Can access admin dashboard' },
  { id: 'notifications:view', name: 'View Notifications', category: 'Dashboard', description: 'Can view system notifications' },
  { id: 'notifications:manage', name: 'Manage Notifications', category: 'Dashboard', description: 'Can send and manage notifications' }
];

// Mock role permissions data
const rolePermissionsData = {
  1: ['users:view', 'users:create', 'users:edit', 'users:delete', 'polls:view', 'polls:create', 'polls:edit', 'polls:delete', 'complaints:view', 'complaints:edit', 'complaints:delete', 'complaints:assign', 'tenants:view', 'tenants:create', 'tenants:edit', 'tenants:delete', 'reports:view', 'reports:export', 'analytics:view', 'settings:view', 'settings:edit', 'roles:manage', 'dashboard:view', 'notifications:view', 'notifications:manage'],
  2: ['polls:view', 'polls:create', 'polls:edit', 'polls:delete', 'dashboard:view', 'reports:view'],
  3: ['complaints:view', 'complaints:edit', 'complaints:assign', 'dashboard:view', 'users:view'],
  4: ['tenants:view', 'tenants:create', 'tenants:edit', 'tenants:delete', 'dashboard:view']
};

export default function Permissions() {
  const { roleId } = useParams();
  const location = useLocation();
  const navigate = useNavigate();
  const [role, setRole] = useState(null);
  const [rolePermissions, setRolePermissions] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [hasChanges, setHasChanges] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  // Get unique categories for filtering
  const categories = ['All', ...new Set(availablePermissions.map(p => p.category))];

  useEffect(() => {
    // Get role from location state or mock data
    if (location.state?.role) {
      setRole(location.state.role);
    } else {
      // Mock role data if not passed
      const mockRole = {
        id: parseInt(roleId),
        name: `Role ${roleId}`,
        description: 'Mock role description',
        isSystem: false
      };
      setRole(mockRole);
    }

    // Load role permissions
    const permissions = rolePermissionsData[parseInt(roleId)] || [];
    setRolePermissions(permissions);
  }, [roleId, location.state]);

  // Filter permissions
  const filteredPermissions = availablePermissions.filter(permission => {
    const matchesSearch = permission.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         permission.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'All' || permission.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const togglePermission = (permissionId) => {
    if (role?.isSystem) return; // Prevent editing system roles
    
    const updatedPermissions = rolePermissions.includes(permissionId)
      ? rolePermissions.filter(p => p !== permissionId)
      : [...rolePermissions, permissionId];
    
    setRolePermissions(updatedPermissions);
    setHasChanges(true);
  };

  const isPermissionSelected = (permissionId) => {
    return rolePermissions.includes(permissionId);
  };

  const handleSavePermissions = () => {
    // Here you would typically save to backend
    console.log('Saving permissions for role:', role?.id, rolePermissions);
    setHasChanges(false);
    alert('Permissions saved successfully!');
  };

  const handleBackToRoles = () => {
    if (hasChanges) {
      if (window.confirm('You have unsaved changes. Are you sure you want to leave?')) {
        navigate('/admin/users/roles');
      }
    } else {
      navigate('/admin/users/roles');
    }
  };

  if (!role) {
    return (
      <AdminLayout>
        <div className="p-6">
          <div className="text-center">
            <p className="text-gray-500">Loading role information...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="p-6 max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <button
                onClick={handleBackToRoles}
                className="mr-4 p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
              >
                <ArrowLeftIcon className="w-5 h-5" />
              </button>
              <div>
                <h1 className="text-3xl font-bold text-gray-900 font-poppins">
                  Permissions for "{role.name}"
                </h1>
                <p className="text-gray-600 mt-2">{role.description}</p>
              </div>
            </div>
            
            {hasChanges && !role.isSystem && (
              <div className="flex space-x-3">
                <button
                  onClick={() => {
                    // Reset changes
                    const originalPermissions = rolePermissionsData[parseInt(roleId)] || [];
                    setRolePermissions(originalPermissions);
                    setHasChanges(false);
                  }}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSavePermissions}
                  className="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
                >
                  <SaveIcon className="w-4 h-4 mr-2" />
                  Save Changes
                </button>
              </div>
            )}
          </div>
        </div>

        {role.isSystem && (
          <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
            <p className="text-sm text-yellow-800">
              This is a system role. Permissions cannot be modified to maintain system integrity.
            </p>
          </div>
        )}

        {/* Filters */}
        <div className="mb-6 flex flex-col sm:flex-row gap-4">
          <div className="flex-1 max-w-md">
            <input
              type="text"
              placeholder="Search permissions..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <div>
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              {categories.map((category) => (
                <option key={category} value={category}>
                  {category}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Permissions Table */}
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">
              Permissions ({rolePermissions.length} of {availablePermissions.length} assigned)
            </h2>
          </div>
          
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-blue-600">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                    Enabled
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                    Permission
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                    Description
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                    Category
                  </th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-white uppercase tracking-wider">
                    Status
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {filteredPermissions.map((permission) => (
                  <tr 
                    key={permission.id} 
                    className={`hover:bg-gray-50 cursor-pointer ${
                      isPermissionSelected(permission.id) ? 'bg-green-50' : ''
                    }`}
                    onClick={() => !role.isSystem && togglePermission(permission.id)}
                  >
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <input
                          type="checkbox"
                          checked={isPermissionSelected(permission.id)}
                          onChange={() => togglePermission(permission.id)}
                          disabled={role.isSystem}
                          className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded disabled:opacity-50"
                        />
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">
                        {permission.name}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900 max-w-xs">
                        {permission.description}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        {permission.category}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-center">
                      {isPermissionSelected(permission.id) ? (
                        <div className="inline-flex items-center text-green-600">
                          <CheckIcon className="w-4 h-4 mr-1" />
                          <span className="text-xs font-medium">Enabled</span>
                        </div>
                      ) : (
                        <div className="inline-flex items-center text-gray-400">
                          <XIcon className="w-4 h-4 mr-1" />
                          <span className="text-xs font-medium">Disabled</span>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          {filteredPermissions.length === 0 && (
            <div className="px-6 py-12 text-center">
              <ShieldIcon className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-500">No permissions found matching your search criteria.</p>
            </div>
          )}
        </div>

        {/* Summary */}
        {hasChanges && (
          <div className="mt-6 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <CheckIcon className="h-5 w-5 text-yellow-400" />
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-yellow-800">
                  Unsaved Changes
                </h3>
                <div className="mt-2 text-sm text-yellow-700">
                  <p>You have unsaved permission changes. Click "Save Changes" to apply them or "Cancel" to discard.</p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}
