import React, { useState } from 'react';

export default function CategoryEditor({ category, onClose, onSave, onDelete }) {
  const categoryData = category || {
    id: 'new',
    name: '',
    channels: [],
  };

  const [name, setName] = useState(categoryData.name);
  const [isPrivate, setIsPrivate] = useState(false);
  const [syncPermissions, setSyncPermissions] = useState(true);

  const availableRoles = [
    { id: 'founder', name: 'Founder', color: '#ff0000' },
    { id: 'foundation', name: 'Foundation', color: '#ff0000' },
    { id: 'corporation', name: 'Corporation', color: '#0066ff' },
    { id: 'labs', name: 'Labs', color: '#ffa500' },
    { id: 'everyone', name: '@everyone', color: '#99aab5' },
  ];

  const [allowedRoles, setAllowedRoles] = useState(['everyone']);

  const toggleRole = (roleId) => {
    setAllowedRoles(prev =>
      prev.includes(roleId)
        ? prev.filter(id => id !== roleId)
        : [...prev, roleId]
    );
  };

  const handleSave = () => {
    onSave?.({
      id: categoryData.id,
      name: name.toUpperCase(),
      isPrivate,
      allowedRoles,
      syncPermissions,
    });
  };

  const isNew = !category?.name;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="category-editor" onClick={(e) => e.stopPropagation()}>
        <div className="category-editor-header">
          <h2>{isNew ? 'Create Category' : 'Edit Category'}</h2>
          <button className="category-close" onClick={onClose}>✕</button>
        </div>

        <div className="category-editor-content">
          <div className="setting-group">
            <label>Category Name</label>
            <input
              type="text"
              className="category-name-input"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="New Category"
              maxLength={100}
            />
          </div>

          <div className="setting-group toggle-group">
            <div className="toggle-info">
              <label>Private Category</label>
              <p className="setting-hint">Only selected roles can view this category</p>
            </div>
            <label className="toggle-switch">
              <input
                type="checkbox"
                checked={isPrivate}
                onChange={(e) => setIsPrivate(e.target.checked)}
              />
              <span className="toggle-slider"></span>
            </label>
          </div>

          {isPrivate && (
            <div className="setting-group">
              <label>Who can view this category?</label>
              <div className="role-selector">
                {availableRoles.map(role => (
                  <label
                    key={role.id}
                    className={`role-checkbox ${allowedRoles.includes(role.id) ? 'checked' : ''}`}
                  >
                    <input
                      type="checkbox"
                      checked={allowedRoles.includes(role.id)}
                      onChange={() => toggleRole(role.id)}
                    />
                    <span className="role-color" style={{ background: role.color }}></span>
                    <span className="role-name">{role.name}</span>
                  </label>
                ))}
              </div>
            </div>
          )}

          {!isNew && categoryData.channels?.length > 0 && (
            <div className="setting-group toggle-group">
              <div className="toggle-info">
                <label>Sync Permissions</label>
                <p className="setting-hint">
                  Sync permissions with {categoryData.channels.length} channels in this category
                </p>
              </div>
              <label className="toggle-switch">
                <input
                  type="checkbox"
                  checked={syncPermissions}
                  onChange={(e) => setSyncPermissions(e.target.checked)}
                />
                <span className="toggle-slider"></span>
              </label>
            </div>
          )}

          {!isNew && (
            <div className="category-channels">
              <label>Channels in this Category</label>
              <div className="channel-list-preview">
                {(categoryData.channels?.length > 0 ? categoryData.channels : [
                  { id: 'general', name: 'general', type: 'text' },
                  { id: 'api-discussion', name: 'api-discussion', type: 'text' },
                ]).map(ch => (
                  <div key={ch.id} className="channel-preview-item">
                    <span className="channel-icon">{ch.type === 'voice' ? '🔊' : '#'}</span>
                    <span>{ch.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="category-editor-footer">
          {!isNew && (
            <button className="delete-category-btn" onClick={onDelete}>
              Delete Category
            </button>
          )}
          <div className="footer-actions">
            <button className="cancel-btn" onClick={onClose}>Cancel</button>
            <button className="save-btn" onClick={handleSave} disabled={!name.trim()}>
              {isNew ? 'Create Category' : 'Save Changes'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
