import React, { useState } from 'react';

const permissionCategories = [
  {
    name: 'General Channel Permissions',
    permissions: [
      { id: 'view_channel', label: 'View Channel', description: 'Allows members to view this channel' },
      { id: 'manage_channel', label: 'Manage Channel', description: 'Allows members to change name, description, and settings' },
      { id: 'manage_permissions', label: 'Manage Permissions', description: 'Allows members to change permission overrides' },
      { id: 'manage_webhooks', label: 'Manage Webhooks', description: 'Allows members to create, edit and delete webhooks' },
    ]
  },
  {
    name: 'Text Channel Permissions',
    permissions: [
      { id: 'send_messages', label: 'Send Messages', description: 'Allows members to send messages in this channel' },
      { id: 'send_messages_threads', label: 'Send Messages in Threads', description: 'Allows members to send messages in threads' },
      { id: 'create_public_threads', label: 'Create Public Threads', description: 'Allows members to create public threads' },
      { id: 'create_private_threads', label: 'Create Private Threads', description: 'Allows members to create private threads' },
      { id: 'embed_links', label: 'Embed Links', description: 'Links will show preview embeds' },
      { id: 'attach_files', label: 'Attach Files', description: 'Allows members to upload files and images' },
      { id: 'add_reactions', label: 'Add Reactions', description: 'Allows members to add reactions to messages' },
      { id: 'use_external_emoji', label: 'Use External Emoji', description: 'Allows members to use emoji from other servers' },
      { id: 'use_external_stickers', label: 'Use External Stickers', description: 'Allows members to use stickers from other servers' },
      { id: 'mention_everyone', label: 'Mention @everyone', description: 'Allows members to mention @everyone and @here' },
      { id: 'manage_messages', label: 'Manage Messages', description: 'Allows members to delete and pin messages' },
      { id: 'manage_threads', label: 'Manage Threads', description: 'Allows members to rename, delete, and archive threads' },
      { id: 'read_message_history', label: 'Read Message History', description: 'Allows reading of message history' },
      { id: 'send_tts', label: 'Send TTS Messages', description: 'Allows sending text-to-speech messages' },
      { id: 'use_application_commands', label: 'Use Application Commands', description: 'Allows using slash commands' },
    ]
  },
  {
    name: 'Voice Channel Permissions',
    permissions: [
      { id: 'connect', label: 'Connect', description: 'Allows members to join this voice channel' },
      { id: 'speak', label: 'Speak', description: 'Allows members to speak in this voice channel' },
      { id: 'video', label: 'Video', description: 'Allows members to share video or stream' },
      { id: 'mute_members', label: 'Mute Members', description: 'Allows muting other members' },
      { id: 'deafen_members', label: 'Deafen Members', description: 'Allows deafening other members' },
      { id: 'move_members', label: 'Move Members', description: 'Allows moving members between voice channels' },
      { id: 'use_vad', label: 'Use Voice Activity', description: 'Allows using voice activity detection instead of push-to-talk' },
      { id: 'priority_speaker', label: 'Priority Speaker', description: 'Allows using priority speaker mode' },
      { id: 'request_to_speak', label: 'Request to Speak', description: 'Allows requesting to speak in stage channels' },
    ]
  }
];

export default function ChannelPermissions({ target, channelName, onClose, onSave }) {
  const targetData = target || {
    id: 'mod',
    name: 'Moderator',
    type: 'role',
    color: '#5865f2',
  };

  const [permissions, setPermissions] = useState({});
  const [searchQuery, setSearchQuery] = useState('');

  const getPermState = (permId) => permissions[permId] || 'neutral';

  const cyclePermission = (permId) => {
    setPermissions(prev => {
      const current = prev[permId] || 'neutral';
      const next = current === 'neutral' ? 'allow' : current === 'allow' ? 'deny' : 'neutral';
      return { ...prev, [permId]: next };
    });
  };

  const setAllPermissions = (state) => {
    const newPerms = {};
    permissionCategories.forEach(cat => {
      cat.permissions.forEach(perm => {
        newPerms[perm.id] = state;
      });
    });
    setPermissions(newPerms);
  };

  const handleSave = () => {
    onSave?.(permissions);
  };

  const filteredCategories = permissionCategories.map(cat => ({
    ...cat,
    permissions: cat.permissions.filter(p =>
      p.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.description.toLowerCase().includes(searchQuery.toLowerCase())
    )
  })).filter(cat => cat.permissions.length > 0);

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="channel-permissions-modal" onClick={(e) => e.stopPropagation()}>
        <div className="permissions-header">
          <div className="permissions-title">
            <h2>Edit Permissions</h2>
            <span className="permissions-context">
              {targetData.type === 'role' ? '@' : ''}
              <span style={targetData.color ? { color: targetData.color } : {}}>
                {targetData.name}
              </span>
              <span className="channel-ref">in #{channelName || 'general'}</span>
            </span>
          </div>
          <button className="permissions-close" onClick={onClose}>✕</button>
        </div>

        <div className="permissions-toolbar">
          <input
            type="text"
            className="permissions-search"
            placeholder="Search permissions..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
          <div className="bulk-actions">
            <button onClick={() => setAllPermissions('allow')}>Allow All</button>
            <button onClick={() => setAllPermissions('neutral')}>Clear All</button>
            <button onClick={() => setAllPermissions('deny')}>Deny All</button>
          </div>
        </div>

        <div className="permissions-legend">
          <div className="legend-item">
            <span className="legend-icon allow">✓</span>
            <span>Allow</span>
          </div>
          <div className="legend-item">
            <span className="legend-icon neutral">/</span>
            <span>Inherit</span>
          </div>
          <div className="legend-item">
            <span className="legend-icon deny">✕</span>
            <span>Deny</span>
          </div>
        </div>

        <div className="permissions-list">
          {filteredCategories.map(category => (
            <div key={category.name} className="permission-category">
              <h3>{category.name}</h3>
              {category.permissions.map(perm => (
                <div key={perm.id} className="permission-row">
                  <div className="permission-info">
                    <span className="permission-label">{perm.label}</span>
                    <span className="permission-desc">{perm.description}</span>
                  </div>
                  <div className="permission-toggles">
                    <button
                      className={`perm-btn allow ${getPermState(perm.id) === 'allow' ? 'active' : ''}`}
                      onClick={() => setPermissions(p => ({ ...p, [perm.id]: 'allow' }))}
                    >
                      ✓
                    </button>
                    <button
                      className={`perm-btn neutral ${getPermState(perm.id) === 'neutral' ? 'active' : ''}`}
                      onClick={() => setPermissions(p => ({ ...p, [perm.id]: 'neutral' }))}
                    >
                      /
                    </button>
                    <button
                      className={`perm-btn deny ${getPermState(perm.id) === 'deny' ? 'active' : ''}`}
                      onClick={() => setPermissions(p => ({ ...p, [perm.id]: 'deny' }))}
                    >
                      ✕
                    </button>
                  </div>
                </div>
              ))}
            </div>
          ))}
        </div>

        <div className="permissions-footer">
          <button className="cancel-btn" onClick={onClose}>Cancel</button>
          <button className="save-btn" onClick={handleSave}>Save Permissions</button>
        </div>
      </div>
    </div>
  );
}
