import { useState, useEffect, useRef } from 'react';
import { Skeleton, Box, IconButton, Collapse, FormControlLabel, Switch, ToggleButtonGroup, ToggleButton, Select, MenuItem, FormControl, InputLabel, Typography } from '@mui/material';
import { VolumeUp, PlayArrow, Pause, Settings, Stop } from '@mui/icons-material';
import GenericWidget from './GenericWidget';

function BriefingWidget({ briefing, sx }) {
  const [showControls, setShowControls] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [autoPlay, setAutoPlay] = useState(false);
  const [playbackSpeed, setPlaybackSpeed] = useState(1);
  const [voices, setVoices] = useState([]);
  const [selectedVoice, setSelectedVoice] = useState('');
  const utteranceRef = useRef(null);

  // Load available voices
  useEffect(() => {
    const loadVoices = () => {
      const availableVoices = window.speechSynthesis.getVoices();
      setVoices(availableVoices);
      
      // Set default voice if not already set
      if (!selectedVoice && availableVoices.length > 0) {
        // First priority: Environment variable
        const envVoice = import.meta.env.REACT_APP_TEXT_VOICE;
        if (envVoice && availableVoices.find(v => v.name === envVoice)) {
          setSelectedVoice(envVoice);
        } else {
          // Second priority: Saved voice in localStorage
          const savedVoice = localStorage.getItem('ttsSelectedVoice');
          if (savedVoice && availableVoices.find(v => v.name === savedVoice)) {
            setSelectedVoice(savedVoice);
          } else {
            // Third priority: Try to find an English voice as default
            const englishVoice = availableVoices.find(v => v.lang.startsWith('en'));
            setSelectedVoice(englishVoice ? englishVoice.name : availableVoices[0].name);
          }
        }
      }
    };

    loadVoices();
    // Some browsers load voices asynchronously
    window.speechSynthesis.addEventListener('voiceschanged', loadVoices);
    
    return () => {
      window.speechSynthesis.removeEventListener('voiceschanged', loadVoices);
    };
  }, [selectedVoice]);

  // Load saved preferences
  useEffect(() => {
    const savedPrefs = localStorage.getItem('ttsPreferences');
    if (savedPrefs) {
      const prefs = JSON.parse(savedPrefs);
      setAutoPlay(prefs.autoPlay || false);
      setPlaybackSpeed(prefs.speed || 1);
    }
  }, []);

  // Save preferences when they change
  useEffect(() => {
    localStorage.setItem('ttsPreferences', JSON.stringify({
      autoPlay,
      speed: playbackSpeed
    }));
    if (selectedVoice) {
      localStorage.setItem('ttsSelectedVoice', selectedVoice);
    }
  }, [autoPlay, playbackSpeed, selectedVoice]);

  // Auto-play on load if enabled and briefing is available
  useEffect(() => {
    if (autoPlay && briefing && !isPlaying) {
      // Small delay to ensure the component is fully mounted
      const timer = setTimeout(() => handlePlay(), 500);
      return () => clearTimeout(timer);
    }
  }, [autoPlay, briefing]);

  const handlePlay = () => {
    if (!briefing) return;

    // Stop any existing speech
    window.speechSynthesis.cancel();

    const utterance = new SpeechSynthesisUtterance(briefing);
    utterance.rate = playbackSpeed;
    
    // Set the selected voice
    if (selectedVoice && voices.length > 0) {
      const voice = voices.find(v => v.name === selectedVoice);
      if (voice) {
        utterance.voice = voice;
      }
    }
    
    utterance.onstart = () => {
      setIsPlaying(true);
      setIsPaused(false);
    };
    
    utterance.onend = () => {
      setIsPlaying(false);
      setIsPaused(false);
      utteranceRef.current = null;
    };
    
    utterance.onerror = (event) => {
      console.error('Speech synthesis error:', event);
      setIsPlaying(false);
      setIsPaused(false);
      utteranceRef.current = null;
    };

    utteranceRef.current = utterance;
    window.speechSynthesis.speak(utterance);
  };

  const handlePause = () => {
    if (window.speechSynthesis.speaking && !isPaused) {
      window.speechSynthesis.pause();
      setIsPaused(true);
    }
  };

  const handleResume = () => {
    if (isPaused) {
      window.speechSynthesis.resume();
      setIsPaused(false);
    }
  };

  const handleStop = () => {
    window.speechSynthesis.cancel();
    setIsPlaying(false);
    setIsPaused(false);
    utteranceRef.current = null;
  };

  const handleSpeedChange = (event, newSpeed) => {
    if (newSpeed !== null) {
      setPlaybackSpeed(newSpeed);
      // If currently playing, restart with new speed
      if (isPlaying) {
        handleStop();
        setTimeout(() => handlePlay(), 100);
      }
    }
  };

  const toggleControls = () => {
    setShowControls(!showControls);
  };

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      window.speechSynthesis.cancel();
    };
  }, []);

  return (
    <GenericWidget
      title="Your Daily Briefing"
      sx={{ ...sx }}
      headerAction={
        briefing && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            {!showControls && !isPlaying && (
              <IconButton 
                size="small" 
                onClick={handlePlay}
                title="Read aloud"
              >
                <VolumeUp />
              </IconButton>
            )}
            {isPlaying && !showControls && (
              <IconButton 
                size="small" 
                onClick={isPaused ? handleResume : handlePause}
                title={isPaused ? "Resume" : "Pause"}
              >
                {isPaused ? <PlayArrow /> : <Pause />}
              </IconButton>
            )}
            <IconButton 
              size="small" 
              onClick={toggleControls}
              title="Audio controls"
            >
              <Settings />
            </IconButton>
          </Box>
        )
      }
    >
      {/* Audio Controls Panel */}
      {briefing && (
        <Collapse in={showControls}>
          <Box sx={{ 
            p: 2, 
            mb: 2, 
            bgcolor: 'action.hover',
            borderRadius: 1,
            display: 'flex',
            alignItems: 'center',
            gap: 2,
            flexWrap: 'wrap'
          }}>
            {/* Play/Pause Button */}
            <Box sx={{ display: 'flex', gap: 1 }}>
              {!isPlaying ? (
                <IconButton 
                  size="medium" 
                  onClick={handlePlay}
                  color="primary"
                  title="Play"
                  sx={{ bgcolor: 'action.hover' }}
                >
                  <PlayArrow />
                </IconButton>
              ) : (
                <>
                  <IconButton 
                    size="medium" 
                    onClick={isPaused ? handleResume : handlePause}
                    color="primary"
                    title={isPaused ? "Resume" : "Pause"}
                    sx={{ bgcolor: 'action.hover' }}
                  >
                    {isPaused ? <PlayArrow /> : <Pause />}
                  </IconButton>
                  <IconButton 
                    size="medium" 
                    onClick={handleStop}
                    title="Stop"
                    sx={{ bgcolor: 'action.hover', color: 'black' }}
                  >
                    <Stop />
                  </IconButton>
                </>
              )}
            </Box>

            {/* Voice Selection */}
            <Box sx={{ minWidth: 200 }}>
              <FormControl size="small" fullWidth>
                <InputLabel id="voice-select-label">Voice</InputLabel>
                <Select
                  labelId="voice-select-label"
                  value={selectedVoice}
                  label="Voice"
                  onChange={(e) => {
                    setSelectedVoice(e.target.value);
                    // If currently playing, restart with new voice
                    if (isPlaying) {
                      handleStop();
                      setTimeout(() => handlePlay(), 100);
                    }
                  }}
                  renderValue={(value) => {
                    const voice = voices.find(v => v.name === value);
                    return voice ? `${voice.name.split(' ')[0]} (${voice.lang})` : value;
                  }}
                >
                  <MenuItem disabled>
                    <Typography variant="caption" color="warning.main">
                      Warning: Changing voice will restart playback
                    </Typography>
                  </MenuItem>
                  {voices.map((voice) => (
                    <MenuItem key={voice.name} value={voice.name}>
                      {voice.name} ({voice.lang})
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Box>

            {/* Speed Control */}
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <span style={{ fontSize: '0.875rem' }}>Speed:</span>
              <ToggleButtonGroup
                value={playbackSpeed}
                exclusive
                onChange={handleSpeedChange}
                size="small"
              >
                <ToggleButton value={1}>
                  1x
                </ToggleButton>
                <ToggleButton value={1.5}>
                  1.5x
                </ToggleButton>
                <ToggleButton value={2}>
                  2x
                </ToggleButton>
              </ToggleButtonGroup>
            </Box>

            {/* Auto-play Toggle */}
            <FormControlLabel
              control={
                <Switch 
                  checked={autoPlay} 
                  onChange={(e) => setAutoPlay(e.target.checked)}
                  size="small"
                />
              }
              label="Auto-play"
              sx={{ fontSize: '0.875rem' }}
            />
          </Box>
        </Collapse>
      )}

      {/* Briefing Content */}
      <Box sx={{ mt: 1 }}>
        {briefing ? (
          <p className="briefing-text">{briefing}</p>
        ) : (
          <>
            <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
            <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
            <Skeleton variant="text" sx={{ fontSize: '1rem', mb: 1 }} />
            <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
            <Skeleton variant="text" sx={{ fontSize: '1rem' }} />
          </>
        )}
      </Box>
    </GenericWidget>
  );
}

export default BriefingWidget;
