import * as React from 'react';
import { useState } from 'react';
import { X, Key, Save, AlertTriangle } from 'lucide-react';
import { roleApi } from '../../services/api';

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

interface PermissionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (permission: Permission) => void;
  mode: 'create' | 'edit';
  permission?: Permission | null;
  existingPermissions?: Permission[]; // Add existing permissions to get unique resources/actions
}

const PermissionModal: React.FC<PermissionModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  mode,
  permission = null,
  existingPermissions = []
}) => {
  const [formData, setFormData] = useState({
    name: permission?.name || '',
    description: permission?.description || '',
    resource: permission?.resource || '',
    action: permission?.action || ''
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Extract unique resources and actions from existing permissions
  const availableResources = React.useMemo(() => {
    const resources = new Set<string>();
    existingPermissions.forEach(perm => {
      resources.add(perm.resource);
    });
    return Array.from(resources).sort();
  }, [existingPermissions]);

  const availableActions = React.useMemo(() => {
    const actions = new Set<string>();
    existingPermissions.forEach(perm => {
      actions.add(perm.action);
    });
    return Array.from(actions).sort();
  }, [existingPermissions]);

  // Update form data when permission prop changes (for edit mode)
  React.useEffect(() => {
    if (permission) {
      setFormData({
        name: permission.name || '',
        description: permission.description || '',
        resource: permission.resource || '',
        action: permission.action || ''
      });
    } else {
      setFormData({
        name: '',
        description: '',
        resource: '',
        action: ''
      });
    }
  }, [permission]);

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

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

    try {
      // Validate form data
      if (!formData.name.trim()) {
        throw new Error('Permission name is required');
      }
      if (!formData.description.trim()) {
        throw new Error('Permission description is required');
      }
      if (!formData.resource.trim()) {
        throw new Error('Resource is required');
      }
      if (!formData.action.trim()) {
        throw new Error('Action is required');
      }

      const permissionData = {
        name: formData.name.trim(),
        description: formData.description.trim(),
        resource: formData.resource.trim(),
        action: formData.action.trim()
      };

      let response;
      if (mode === 'create') {
        response = await roleApi.createPermission(permissionData);
      } else {
        response = await roleApi.updatePermission(permission.id!, permissionData);
      }

      if (response.status === 'success') {
        const newPermission: Permission = {
          id: mode === 'edit' && permission ? permission.id : response.data.permission.id,
          name: permissionData.name,
          description: permissionData.description,
          resource: permissionData.resource,
          action: permissionData.action
        };

        onSuccess(newPermission);
        handleClose();
      } else {
        throw new Error(response.message || 'Failed to save permission');
      }
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    if (!loading) {
      setFormData({
        name: '',
        description: '',
        resource: '',
        action: ''
      });
      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-green-600 rounded-full flex items-center justify-center">
              <Key className="h-5 w-5 text-white" />
            </div>
            <h2 className="text-xl font-semibold text-gray-900">
              {mode === 'create' ? 'Add New Permission' : 'Edit Permission'}
            </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">
            {/* Permission Name */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Permission 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-green-500 disabled:opacity-50"
                placeholder="e.g., user.create, message.read"
              />
            </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-green-500 disabled:opacity-50 resize-none"
                placeholder="Describe what this permission allows"
              />
            </div>

            {/* Resource */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Resource *
              </label>
              <select
                name="resource"
                value={formData.resource}
                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-green-500 disabled:opacity-50"
              >
                <option value="">Select Resource</option>
                {availableResources.map(resource => (
                  <option key={resource} value={resource}>
                    {resource.charAt(0).toUpperCase() + resource.slice(1).replace('_', ' ')}
                  </option>
                ))}
              </select>
            </div>

            {/* Action */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Action *
              </label>
              <select
                name="action"
                value={formData.action}
                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-green-500 disabled:opacity-50"
              >
                <option value="">Select Action</option>
                {availableActions.map(action => (
                  <option key={action} value={action}>
                    {action.charAt(0).toUpperCase() + action.slice(1).replace('_', ' ')}
                  </option>
                ))}
              </select>
            </div>

            {/* Permission Preview */}
            <div className="bg-gray-50 p-3 rounded-lg">
              <p className="text-sm text-gray-600">
                <span className="font-medium">Permission:</span> {formData.name || 'permission.name'}
              </p>
              <p className="text-sm text-gray-600">
                <span className="font-medium">Description:</span> {formData.description || 'Permission description'}
              </p>
              <p className="text-sm text-gray-600">
                <span className="font-medium">Access:</span> {formData.action || 'action'} {formData.resource || 'resource'}
              </p>
            </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-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-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 Permission' : 'Update Permission'}</span>
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default PermissionModal;
