import React, { useState } from 'react';

const permissions = [
  { category: 'General', items: [
    { id: 'view_channels', label: 'View Channels', description: 'Members can view channels by default' },
    { id: 'manage_channels', label: 'Manage Channels', description: 'Create, edit, and delete channels', dangerous: true },
    { id: 'manage_roles', label: 'Manage Roles', description: 'Create and edit roles below this one', dangerous: true },
    { id: 'manage_emoji', label: 'Manage Emoji & Stickers', description: 'Add, remove, and manage custom emojis' },
    { id: 'view_audit', label: 'View Audit Log', description: 'View a log of all moderation actions' },
    { id: 'manage_webhooks', label: 'Manage Webhooks', description: 'Create, edit, and delete webhooks' },
    { id: 'manage_server', label: 'Manage Server', description: 'Change server name, region, etc.', dangerous: true },
  ]},
  { category: 'Membership', items: [
    { id: 'create_invite', label: 'Create Invite', description: 'Invite new people to this server' },
    { id: 'change_nickname', label: 'Change Nickname', description: 'Change their own nickname' },
    { id: 'manage_nicknames', label: 'Manage Nicknames', description: 'Change nicknames of other members' },
    { id: 'kick_members', label: 'Kick Members', description: 'Remove members from the server', dangerous: true },
    { id: 'ban_members', label: 'Ban Members', description: 'Permanently ban members', dangerous: true },
    { id: 'timeout_members', label: 'Timeout Members', description: 'Temporarily mute members' },
  ]},
  { category: 'Text', items: [
    { id: 'send_messages', label: 'Send Messages', description: 'Send messages in text channels' },
    { id: 'send_tts', label: 'Send TTS Messages', description: 'Send text-to-speech messages' },
    { id: 'manage_messages', label: 'Manage Messages', description: 'Delete and pin messages from others', dangerous: true },
    { id: 'embed_links', label: 'Embed Links', description: 'Links will show a preview' },
    { id: 'attach_files', label: 'Attach Files', description: 'Upload images and files' },
    { id: 'add_reactions', label: 'Add Reactions', description: 'React to messages with emoji' },
    { id: 'use_external_emoji', label: 'Use External Emoji', description: 'Use emoji from other servers' },
    { id: 'mention_everyone', label: 'Mention @everyone', description: 'Can use @everyone and @here', dangerous: true },
  ]},
  { category: 'Voice', items: [
    { id: 'connect', label: 'Connect', description: 'Join voice channels' },
    { id: 'speak', label: 'Speak', description: 'Talk in voice channels' },
    { id: 'video', label: 'Video', description: 'Share camera in voice channels' },
    { id: 'mute_members', label: 'Mute Members', description: 'Mute other members' },
    { id: 'deafen_members', label: 'Deafen Members', description: 'Deafen other members' },
    { id: 'move_members', label: 'Move Members', description: 'Move members between voice channels' },
    { id: 'use_vad', label: 'Use Voice Activity', description: 'Use voice activity detection' },
    { id: 'priority_speaker', label: 'Priority Speaker', description: 'Be more easily heard' },
  ]},
];

export default function RoleEditor({ role, onSave, onClose }) {
  const [roleName, setRoleName] = useState(role?.name || 'New Role');
  const [roleColor, setRoleColor] = useState(role?.color || '#99aab5');
  const [rolePermissions, setRolePermissions] = useState(role?.permissions || {});
  const [displaySeparately, setDisplaySeparately] = useState(role?.displaySeparately || false);
  const [mentionable, setMentionable] = useState(role?.mentionable || false);
  const [activeTab, setActiveTab] = useState('display');

  const colors = [
    '#99aab5', '#1abc9c', '#2ecc71', '#3498db', '#9b59b6',
    '#e91e63', '#f1c40f', '#e67e22', '#e74c3c', '#95a5a6',
    '#607d8b', '#11806a', '#1f8b4c', '#206694', '#71368a',
    '#ad1457', '#c27c0e', '#a84300', '#992d22', '#979c9f',
  ];

  const togglePermission = (permId) => {
    setRolePermissions(prev => ({
      ...prev,
      [permId]: prev[permId] === true ? false : prev[permId] === false ? null : true
    }));
  };

  const getPermState = (permId) => {
    const state = rolePermissions[permId];
    if (state === true) return 'granted';
    if (state === false) return 'denied';
    return 'inherit';
  };

  return (
    <div className="role-editor">
      <div className="role-editor-sidebar">
        <div className="role-preview">
          <div className="role-color-preview" style={{ background: roleColor }} />
          <input 
            type="text" 
            value={roleName}
            onChange={(e) => setRoleName(e.target.value)}
            className="role-name-input"
          />
        </div>

        <div className="editor-tabs">
          <button 
            className={`editor-tab ${activeTab === 'display' ? 'active' : ''}`}
            onClick={() => setActiveTab('display')}
          >
            Display
          </button>
          <button 
            className={`editor-tab ${activeTab === 'permissions' ? 'active' : ''}`}
            onClick={() => setActiveTab('permissions')}
          >
            Permissions
          </button>
          <button 
            className={`editor-tab ${activeTab === 'members' ? 'active' : ''}`}
            onClick={() => setActiveTab('members')}
          >
            Members
          </button>
        </div>
      </div>

      <div className="role-editor-content">
        <div className="editor-header">
          <h2>Edit Role — {roleName}</h2>
          <button className="editor-close" onClick={onClose}>✕</button>
        </div>

        {activeTab === 'display' && (
          <div className="editor-section">
            <div className="setting-group">
              <label>Role Name</label>
              <input
                type="text"
                value={roleName}
                onChange={(e) => setRoleName(e.target.value)}
                className="text-input"
              />
            </div>

            <div className="setting-group">
              <label>Role Color</label>
              <div className="color-grid">
                {colors.map(color => (
                  <button
                    key={color}
                    className={`color-btn ${roleColor === color ? 'selected' : ''}`}
                    style={{ background: color }}
                    onClick={() => setRoleColor(color)}
                  />
                ))}
              </div>
              <div className="custom-color">
                <input
                  type="color"
                  value={roleColor}
                  onChange={(e) => setRoleColor(e.target.value)}
                />
                <input
                  type="text"
                  value={roleColor}
                  onChange={(e) => setRoleColor(e.target.value)}
                  className="color-text-input"
                />
              </div>
            </div>

            <div className="setting-group">
              <label className="toggle-setting">
                <div className="setting-info">
                  <span>Display role members separately</span>
                  <span className="setting-desc">Show members with this role in a separate category</span>
                </div>
                <input
                  type="checkbox"
                  checked={displaySeparately}
                  onChange={(e) => setDisplaySeparately(e.target.checked)}
                />
              </label>
            </div>

            <div className="setting-group">
              <label className="toggle-setting">
                <div className="setting-info">
                  <span>Allow anyone to @mention this role</span>
                  <span className="setting-desc">Members can mention this role in chat</span>
                </div>
                <input
                  type="checkbox"
                  checked={mentionable}
                  onChange={(e) => setMentionable(e.target.checked)}
                />
              </label>
            </div>

            <div className="role-icon-section">
              <label>Role Icon</label>
              <div className="role-icon-upload">
                <div className="icon-placeholder">🎭</div>
                <button className="upload-icon-btn">Upload Image</button>
                <span className="icon-hint">Recommended 64x64</span>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'permissions' && (
          <div className="editor-section permissions-section">
            <div className="permissions-warning">
              ⚠️ Be careful! Granting dangerous permissions can allow members to harm your server.
            </div>

            {permissions.map(category => (
              <div key={category.category} className="permission-category">
                <h3>{category.category}</h3>
                {category.items.map(perm => (
                  <div 
                    key={perm.id} 
                    className={`permission-item ${perm.dangerous ? 'dangerous' : ''}`}
                  >
                    <div className="perm-info">
                      <span className="perm-label">{perm.label}</span>
                      <span className="perm-description">{perm.description}</span>
                    </div>
                    <div className="perm-toggle">
                      <button 
                        className={`toggle-btn ${getPermState(perm.id) === 'denied' ? 'active' : ''}`}
                        onClick={() => setRolePermissions(prev => ({ ...prev, [perm.id]: false }))}
                      >
                        ✕
                      </button>
                      <button 
                        className={`toggle-btn neutral ${getPermState(perm.id) === 'inherit' ? 'active' : ''}`}
                        onClick={() => setRolePermissions(prev => ({ ...prev, [perm.id]: null }))}
                      >
                        /
                      </button>
                      <button 
                        className={`toggle-btn ${getPermState(perm.id) === 'granted' ? 'active' : ''}`}
                        onClick={() => setRolePermissions(prev => ({ ...prev, [perm.id]: true }))}
                      >
                        ✓
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ))}
          </div>
        )}

        {activeTab === 'members' && (
          <div className="editor-section">
            <div className="members-header">
              <input type="text" placeholder="Search members" className="members-search" />
              <button className="add-members-btn">+ Add Members</button>
            </div>
            <div className="role-members-list">
              <div className="member-item">
                <div className="member-avatar" style={{ background: '#ff0000' }}>T</div>
                <span className="member-name">Trevor</span>
                <button className="remove-member-btn">✕</button>
              </div>
              <div className="member-item">
                <div className="member-avatar" style={{ background: '#ffa500' }}>S</div>
                <span className="member-name">Sarah</span>
                <button className="remove-member-btn">✕</button>
              </div>
            </div>
          </div>
        )}

        <div className="editor-footer">
          <button className="delete-role-btn">Delete Role</button>
          <div className="footer-actions">
            <button className="cancel-btn" onClick={onClose}>Cancel</button>
            <button 
              className="save-btn"
              onClick={() => onSave?.({ name: roleName, color: roleColor, permissions: rolePermissions, displaySeparately, mentionable })}
            >
              Save Changes
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
