import React, { useState } from 'react';

const slowModePresets = [
  { value: 0, label: 'Off' },
  { value: 5, label: '5s' },
  { value: 10, label: '10s' },
  { value: 15, label: '15s' },
  { value: 30, label: '30s' },
  { value: 60, label: '1m' },
  { value: 120, label: '2m' },
  { value: 300, label: '5m' },
  { value: 600, label: '10m' },
  { value: 900, label: '15m' },
  { value: 1800, label: '30m' },
  { value: 3600, label: '1h' },
  { value: 7200, label: '2h' },
  { value: 21600, label: '6h' },
];

export default function SlowModeSettings({ channel, onSave, onClose }) {
  const [slowMode, setSlowMode] = useState(channel?.slowMode || 0);
  const [customMode, setCustomMode] = useState(false);
  const [customSeconds, setCustomSeconds] = useState('');
  const [exemptRoles, setExemptRoles] = useState(channel?.exemptRoles || []);
  const [showExemptSettings, setShowExemptSettings] = useState(false);

  const roles = [
    { id: 'admin', name: 'Admin', color: '#ff0000' },
    { id: 'mod', name: 'Moderator', color: '#5865f2' },
    { id: 'helper', name: 'Helper', color: '#3ba55d' },
    { id: 'vip', name: 'VIP', color: '#faa61a' },
    { id: 'booster', name: 'Server Booster', color: '#ff73fa' },
  ];

  const formatDuration = (seconds) => {
    if (seconds === 0) return 'Off';
    if (seconds < 60) return `${seconds} second${seconds !== 1 ? 's' : ''}`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)} minute${seconds >= 120 ? 's' : ''}`;
    return `${Math.floor(seconds / 3600)} hour${seconds >= 7200 ? 's' : ''}`;
  };

  const handlePresetClick = (value) => {
    setSlowMode(value);
    setCustomMode(false);
  };

  const handleCustomApply = () => {
    const value = parseInt(customSeconds);
    if (!isNaN(value) && value >= 0 && value <= 21600) {
      setSlowMode(value);
      setCustomMode(false);
    }
  };

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

  const handleSave = () => {
    onSave?.({
      slowMode,
      exemptRoles,
    });
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="slowmode-modal" onClick={(e) => e.stopPropagation()}>
        <div className="slowmode-header">
          <h2>⏱️ Slowmode Settings</h2>
          <button className="slowmode-close" onClick={onClose}>✕</button>
        </div>

        <div className="slowmode-content">
          <div className="slowmode-channel">
            <span className="channel-icon">#</span>
            <span className="channel-name">{channel?.name || 'general'}</span>
          </div>

          <div className="slowmode-section">
            <h3>Slowmode Duration</h3>
            <p className="slowmode-description">
              Members can only send one message per {formatDuration(slowMode)}.
            </p>

            <div className="slowmode-presets">
              {slowModePresets.map(preset => (
                <button
                  key={preset.value}
                  className={`preset-btn ${slowMode === preset.value && !customMode ? 'active' : ''}`}
                  onClick={() => handlePresetClick(preset.value)}
                >
                  {preset.label}
                </button>
              ))}
              <button
                className={`preset-btn ${customMode ? 'active' : ''}`}
                onClick={() => setCustomMode(true)}
              >
                Custom
              </button>
            </div>

            {customMode && (
              <div className="custom-input">
                <input
                  type="number"
                  min="0"
                  max="21600"
                  value={customSeconds}
                  onChange={(e) => setCustomSeconds(e.target.value)}
                  placeholder="Seconds (0-21600)"
                />
                <button className="apply-custom" onClick={handleCustomApply}>
                  Apply
                </button>
              </div>
            )}

            <div className="slowmode-slider">
              <input
                type="range"
                min="0"
                max="21600"
                step="5"
                value={slowMode}
                onChange={(e) => setSlowMode(parseInt(e.target.value))}
              />
              <span className="slider-value">{formatDuration(slowMode)}</span>
            </div>
          </div>

          <div className="slowmode-section">
            <div 
              className="section-header-toggle"
              onClick={() => setShowExemptSettings(!showExemptSettings)}
            >
              <h3>Exempt Roles</h3>
              <span className="toggle-icon">{showExemptSettings ? '▼' : '▶'}</span>
            </div>
            
            {showExemptSettings && (
              <div className="exempt-roles">
                <p className="exempt-description">
                  These roles won't be affected by slowmode.
                </p>
                {roles.map(role => (
                  <label key={role.id} className="exempt-role">
                    <input
                      type="checkbox"
                      checked={exemptRoles.includes(role.id)}
                      onChange={() => toggleExemptRole(role.id)}
                    />
                    <span 
                      className="role-name"
                      style={{ color: role.color }}
                    >
                      @{role.name}
                    </span>
                  </label>
                ))}
              </div>
            )}
          </div>

          <div className="slowmode-info">
            <span className="info-icon">ℹ️</span>
            <span>
              Slowmode helps prevent spam by limiting how often members can send messages.
              Members with "Manage Channel" permission are always exempt.
            </span>
          </div>
        </div>

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