import { useState, useEffect, useCallback, useMemo } from 'react';
import { getBrowserTTS } from '../services/browserTTSService';

function TTSSettings({ sessionId, onClose }) {
  const [settings, setSettings] = useState(() => {
    const saved = localStorage.getItem('tts-settings-global');
    return saved ? JSON.parse(saved) : {
      enabled: true,
      autoPlay: false,
      narratorGender: 'Male',
      volume: 1,
      speed: 1,
      pitch: 1
    };
  });
  
  const [ttsSupported, setTtsSupported] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [showVoiceSelector, setShowVoiceSelector] = useState(false);
  const [voiceCount, setVoiceCount] = useState(0);

  // Memoize voice counts to avoid recalculation
  const voiceStats = useMemo(() => {
    const tts = getBrowserTTS();
    const voices = tts.getVoices();
    const maleCount = voices.filter(v => v.gender === 'Male').length;
    const femaleCount = voices.filter(v => v.gender === 'Female').length;
    return { total: voices.length, male: maleCount, female: femaleCount };
  }, [isLoading]);

  useEffect(() => {
    checkSupport();
  }, []);

  const checkSupport = () => {
    const tts = getBrowserTTS();
    
    if (!tts.isSupported()) {
      setTtsSupported(false);
      setIsLoading(false);
      return;
    }

    // Wait for voices to load
    const checkVoices = () => {
      if (tts.isInitialized) {
        setVoiceCount(tts.getVoices().length);
        setIsLoading(false);
      } else {
        setTimeout(checkVoices, 100);
      }
    };
    
    checkVoices();
  };

  const updateSetting = useCallback((key, value) => {
    setSettings(prev => {
      const newSettings = { ...prev, [key]: value };
      localStorage.setItem('tts-settings-global', JSON.stringify(newSettings));
      return newSettings;
    });
  }, []);

  const handleNarratorGenderChange = useCallback((gender) => {
    updateSetting('narratorGender', gender);
    setShowVoiceSelector(false);
  }, [updateSetting]);

  const handleDone = useCallback(() => {
    onClose(settings);
  }, [settings, onClose]);

  const handleTestVoice = useCallback((gender) => {
    const tts = getBrowserTTS();
    const voice = tts.getNarratorVoice(gender);
    console.log('[TTS Test] Voice:', voice?.name);
    
    tts.speak(gender === 'Male' 
      ? 'Hello! I am the male narrator voice. Welcome to your adventure.' 
      : 'Hello! I am the female narrator voice. Welcome to your adventure.',
      {
        voice,
        volume: settings.volume,
        rate: settings.speed,
        pitch: settings.pitch
      }
    );
  }, [settings.volume, settings.speed, settings.pitch]);

  if (!ttsSupported) {
    return (
      <div className="tts-settings-modal">
        <div className="modal-content">
          <div className="modal-header">
            <h3>🔊 Text-to-Speech Settings</h3>
            <button className="modal-close" onClick={handleDone}>×</button>
          </div>
          <div className="modal-body">
            <div className="tts-status">
              <div className="status-indicator unavailable">✗</div>
              <span>Browser does not support Text-to-Speech</span>
            </div>
            <p className="hint">Please use Chrome, Edge, or Safari for TTS support.</p>
          </div>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="tts-settings-modal">
        <div className="modal-content">
          <div className="modal-header">
            <h3>🔊 Text-to-Speech Settings</h3>
            <button className="modal-close" onClick={handleDone}>×</button>
          </div>
          <div className="modal-body">
            <p>Loading voices...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="tts-settings-modal">
      <div className="modal-content">
        <div className="modal-header">
          <h3>🔊 Text-to-Speech Settings</h3>
          <button className="modal-close" onClick={handleDone}>×</button>
        </div>
        
        <div className="modal-body">
          {/* TTS Status */}
          <div className="tts-status">
            <div className="status-indicator available">✓</div>
            <span>Browser TTS Available ({voiceCount} voices)</span>
          </div>

          {/* Enable/Disable TTS */}
          <div className="setting-row">
            <label>
              <input
                type="checkbox"
                checked={settings.enabled}
                onChange={(e) => updateSetting('enabled', e.target.checked)}
              />
              <span>Enable Text-to-Speech</span>
            </label>
          </div>

          {/* Auto-play Toggle */}
          <div className="setting-row">
            <label>
              <input
                type="checkbox"
                checked={settings.autoPlay}
                onChange={(e) => updateSetting('autoPlay', e.target.checked)}
                disabled={!settings.enabled}
              />
              <span>Auto-play narration</span>
            </label>
            <p className="setting-hint">
              {settings.autoPlay 
                ? 'Audio will play automatically when the narrator responds' 
                : 'Click the play button to hear narration'}
            </p>
          </div>

          {/* Narrator Gender Selection */}
          <div className="setting-row">
            <label>Narrator Voice</label>
            <div className="voice-selector">
              <button 
                className="selected-voice-btn"
                onClick={() => setShowVoiceSelector(!showVoiceSelector)}
                disabled={!settings.enabled}
              >
                <span className="voice-icon">
                  {settings.narratorGender === 'Male' ? '👨' : '👩'}
                </span>
                <span className="voice-name">
                  {settings.narratorGender} Narrator
                  ({settings.narratorGender === 'Male' ? voiceStats.male : voiceStats.female} voices)
                </span>
                <span className="voice-arrow">{showVoiceSelector ? '↑' : '↓'}</span>
              </button>

              {showVoiceSelector && (
                <div className="voice-dropdown">
                  <div className="voice-category">
                    <h5>👨 Male Voices ({voiceStats.male})</h5>
                    <button
                      className={`voice-option ${settings.narratorGender === 'Male' ? 'selected' : ''}`}
                      onClick={() => handleNarratorGenderChange('Male')}
                    >
                      <span className="voice-label">Use Male Narrator</span>
                      <span className="voice-desc">Deeper, authoritative tone</span>
                    </button>
                  </div>
                  <div className="voice-category">
                    <h5>👩 Female Voices ({voiceStats.female})</h5>
                    <button
                      className={`voice-option ${settings.narratorGender === 'Female' ? 'selected' : ''}`}
                      onClick={() => handleNarratorGenderChange('Female')}
                    >
                      <span className="voice-label">Use Female Narrator</span>
                      <span className="voice-desc">Warm, engaging tone</span>
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Volume Control */}
          <div className="setting-row">
            <label>Volume: {Math.round(settings.volume * 100)}%</label>
            <input
              type="range"
              min="0"
              max="1"
              step="0.1"
              value={settings.volume}
              onChange={(e) => updateSetting('volume', parseFloat(e.target.value))}
              disabled={!settings.enabled}
              className="volume-slider"
            />
          </div>

          {/* Speed Control */}
          <div className="setting-row">
            <label>Speed: {settings.speed}x</label>
            <input
              type="range"
              min="0.5"
              max="2"
              step="0.1"
              value={settings.speed}
              onChange={(e) => updateSetting('speed', parseFloat(e.target.value))}
              disabled={!settings.enabled}
              className="speed-slider"
            />
          </div>

          {/* Pitch Control */}
          <div className="setting-row">
            <label>Pitch: {settings.pitch}</label>
            <input
              type="range"
              min="0.5"
              max="2"
              step="0.1"
              value={settings.pitch}
              onChange={(e) => updateSetting('pitch', parseFloat(e.target.value))}
              disabled={!settings.enabled}
              className="speed-slider"
            />
          </div>

          {/* Test Buttons */}
          <div className="setting-row">
            <div className="test-buttons-row">
              <button 
                className="test-tts-btn male"
                onClick={() => handleTestVoice('Male')}
                disabled={!settings.enabled}
              >
                👨 Test Male
              </button>
              <button 
                className="test-tts-btn female"
                onClick={() => handleTestVoice('Female')}
                disabled={!settings.enabled}
              >
                👩 Test Female
              </button>
            </div>
          </div>

          {/* Info */}
          <div className="tts-setup-info">
            <h4>ℹ️ About Browser TTS</h4>
            <p>
              Uses your browser's built-in Text-to-Speech. 
              Quality depends on your browser and OS.
            </p>
            <p className="hint">
              Best results: Chrome, Edge, or Safari on desktop.
              Characters will use appropriate gender voices automatically.
            </p>
          </div>
        </div>

        <div className="modal-footer">
          <button className="btn btn-primary" onClick={handleDone}>Done</button>
        </div>
      </div>
    </div>
  );
}

export default TTSSettings;
