import React, { useRef, useState, useEffect } from 'react';
import { Box, Paper, IconButton, Typography, Slider, LinearProgress, Tooltip, Fade, Chip } from '@mui/material';
import {
  PlayArrow,
  Pause,
  VolumeUp,
  VolumeOff,
  SkipNext,
  SkipPrevious,
  Cast,
  CastConnected,
  MusicNote,
  GraphicEq
} from '@mui/icons-material';
import ReactPlayer from 'react-player';
import Logo from './Logo';
import AudioVisualizer from './AudioVisualizer';
import { useChromecast } from '../utils/useChromecast';
import { useAuthStore } from '../store/authStore';
import { useTranslation } from 'react-i18next';
import axios from 'axios';

function AudioPlayer({ station, onNext, onPrevious }) {
  const playerRef = useRef(null);
  const audioElementRef = useRef(null);
  const metadataIntervalRef = useRef(null);
  const { token } = useAuthStore();
  const { t } = useTranslation();
  const [playing, setPlaying] = useState(false);
  const [volume, setVolume] = useState(0.8);
  const [muted, setMuted] = useState(false);
  const [isReady, setIsReady] = useState(false);
  const [showControls, setShowControls] = useState(true);
  const [visualizerType, setVisualizerType] = useState(0);
  const [metadata, setMetadata] = useState(null);
  const [loadingMetadata, setLoadingMetadata] = useState(false);
  const [buffering, setBuffering] = useState(false);
  const hideControlsTimer = useRef(null);
  
  // Chromecast support
  const { 
    castAvailable, 
    casting, 
    castMedia, 
    stopCasting, 
    openCastDialog,
    setCastVolume,
    setCastMuted
  } = useChromecast();

  // Auto-hide controls after 2 seconds when playing
  const resetControlsTimer = () => {
    setShowControls(true);
    if (hideControlsTimer.current) {
      clearTimeout(hideControlsTimer.current);
    }
    if (playing) {
      hideControlsTimer.current = setTimeout(() => {
        setShowControls(false);
      }, 2000);
    }
  };

  // Cleanup timer
  useEffect(() => {
    return () => {
      if (hideControlsTimer.current) {
        clearTimeout(hideControlsTimer.current);
      }
    };
  }, []);

  // Reset timer when playing changes
  useEffect(() => {
    if (playing) {
      resetControlsTimer();
    } else {
      setShowControls(true);
      if (hideControlsTimer.current) {
        clearTimeout(hideControlsTimer.current);
      }
    }
  }, [playing]);

  // Fetch metadata for radio station
  const fetchMetadata = async () => {
    if (!station?.id || !playing) return;
    
    try {
      setLoadingMetadata(true);
      const response = await axios.get(`/api/metadata/radio/${station.id}`, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      
      if (response.data) {
        setMetadata(response.data);
      }
    } catch (error) {
      console.error('[Metadata] Error fetching metadata:', error);
      setMetadata(null);
    } finally {
      setLoadingMetadata(false);
    }
  };

  // Poll metadata when playing
  useEffect(() => {
    if (playing && station?.id) {
      // Fetch immediately
      fetchMetadata();
      
      // Poll every 10 seconds
      metadataIntervalRef.current = setInterval(fetchMetadata, 10000);
    } else {
      // Clear interval when not playing
      if (metadataIntervalRef.current) {
        clearInterval(metadataIntervalRef.current);
        metadataIntervalRef.current = null;
      }
      setMetadata(null);
    }

    return () => {
      if (metadataIntervalRef.current) {
        clearInterval(metadataIntervalRef.current);
      }
    };
  }, [playing, station?.id, token]);

  // Cycle through visualizers every 15 seconds when playing
  useEffect(() => {
    if (!playing) return;

    const cycleInterval = setInterval(() => {
      setVisualizerType(prev => (prev + 1) % 10);
    }, 15000);

    return () => clearInterval(cycleInterval);
  }, [playing]);

  const handlePlayPause = () => {
    setPlaying(!playing);
    resetControlsTimer();
  };

  const handleVolumeChange = (event, newValue) => {
    setVolume(newValue / 100);
    setMuted(newValue === 0);
  };

  const handleToggleMute = () => {
    setMuted(!muted);
  };

  // Get stream URL with token
  const getStreamUrl = () => {
    if (!station?.id) return station?.url || '';
    // Use backend proxy for radio streams
    return `/api/stream/proxy/${station.id}?token=${token}`;
  };

  // Get full URL for Chromecast (needs absolute URL)
  const getFullStreamUrl = () => {
    const streamUrl = station?.url || getStreamUrl();
    if (!streamUrl) return '';
    // If it's already an absolute URL, use it; otherwise make it absolute
    if (streamUrl.startsWith('http')) {
      return streamUrl;
    }
    return `${window.location.origin}${streamUrl}`;
  };

  // Get original station URL for Chromecast (bypasses proxy)
  const getOriginalStationUrl = async () => {
    if (!station?.id) return null;
    
    try {
      // Fetch station data to get original URL
      const response = await fetch(`/api/radio/${station.id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.ok) {
        const stationData = await response.json();
        console.log('[Cast] Original station URL:', stationData.url);
        return stationData.url;
      }
    } catch (error) {
      console.error('[Cast] Error fetching station URL:', error);
    }
    
    return null;
  };

  // Handle Chromecast
  const handleCast = async () => {
    if (casting) {
      // Stop casting
      stopCasting();
      // Resume local playback
      setPlaying(false);
    } else {
      // Start casting
      if (!station) return;
      
      // Pause local playback
      setPlaying(false);
      
      // Try to get original URL first (Chromecast can access it directly)
      const originalUrl = await getOriginalStationUrl();
      const castUrl = originalUrl || getFullStreamUrl();
      
      console.log('[Cast] Casting URL:', castUrl);
      console.log('[Cast] Station:', station.name);
      
      // Detect content type from URL
      let contentType = 'audio/mpeg';
      if (castUrl.includes('.m3u8')) {
        contentType = 'application/x-mpegURL';
      } else if (castUrl.includes('.aac')) {
        contentType = 'audio/aac';
      }
      
      console.log('[Cast] Content type:', contentType);
      
      // Cast the media
      const success = await castMedia({
        url: castUrl,
        title: station.name || 'Radio Station',
        subtitle: station.genre || 'Live Radio',
        contentType: contentType,
        imageUrl: station.logo || '',
        isLive: true
      });
      
      if (!success) {
        console.log('[Cast] Cast failed, opening device selector');
        // If casting failed, open device selector
        openCastDialog();
      } else {
        console.log('[Cast] Cast successful');
      }
    }
  };

  // Sync volume with Chromecast when casting
  useEffect(() => {
    if (casting && setCastVolume) {
      setCastVolume(volume);
    }
  }, [volume, casting, setCastVolume]);

  // Sync mute with Chromecast when casting
  useEffect(() => {
    if (casting && setCastMuted) {
      setCastMuted(muted);
    }
  }, [muted, casting, setCastMuted]);

  return (
    <Paper
      sx={{
        position: 'relative',
        width: '100%',
        minHeight: { xs: 300, md: 180 },
        maxHeight: { xs: 'none', md: 250 },
        bgcolor: 'background.paper',
        borderRadius: 3,
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column'
      }}
    >
      {/* Audio Player - hidden visually but accessible for visualizer */}
      {!casting && (
        <Box sx={{ position: 'absolute', width: 0, height: 0, overflow: 'hidden', pointerEvents: 'none' }}>
          <ReactPlayer
            ref={playerRef}
            url={getStreamUrl()}
            playing={playing}
            volume={volume}
            muted={muted}
            width="100%"
            height="100%"
            progressInterval={5000}
            onReady={() => {
              setIsReady(true);
              setBuffering(false);
            }}
            onPlay={() => {
              setBuffering(false);
              // Capture audio element when actually playing
              if (playerRef.current && !audioElementRef.current) {
                const player = playerRef.current.getInternalPlayer();
                if (player && (player.tagName === 'AUDIO' || player.tagName === 'VIDEO')) {
                  audioElementRef.current = player;
                  console.log('[AudioPlayer] Audio element captured for visualizer');
                }
              }
            }}
            onBuffer={() => setBuffering(true)}
            onBufferEnd={() => setBuffering(false)}
            config={{
              file: {
                forceAudio: true,
                attributes: {
                  crossOrigin: 'anonymous'
                }
              }
            }}
          />
        </Box>
      )}

      {/* Visual Display */}
      <Box
        onMouseMove={resetControlsTimer}
        onTouchStart={resetControlsTimer}
        sx={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          position: 'relative',
          overflow: 'hidden'
        }}
      >
        {/* Audio Visualizer Background */}
        {playing && audioElementRef.current && (
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              zIndex: 0
            }}
          >
            <AudioVisualizer
              audioElement={audioElementRef.current}
              isPlaying={playing && !casting}
              visualizerType={visualizerType}
            />
          </Box>
        )}

        {/* Content Overlay */}
        <Box
          sx={{
            position: 'relative',
            zIndex: 1,
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            background: playing 
              ? 'linear-gradient(135deg, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.5) 100%)'
              : 'linear-gradient(135deg, rgba(168, 85, 247, 0.05) 0%, rgba(59, 130, 246, 0.05) 100%)',
            p: { xs: 4, md: 1.5 },
            gap: { xs: 2, md: 0.5 }
          }}
        >
          {/* Buffering/Loading Indicator */}
          {(buffering || (playing && !isReady)) && (
            <Fade in={true}>
              <Box
                sx={{
                  position: 'absolute',
                  top: 16,
                  left: 16,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1,
                  bgcolor: 'rgba(0, 0, 0, 0.6)',
                  backdropFilter: 'blur(10px)',
                  px: 2,
                  py: 1,
                  borderRadius: 3,
                  color: 'white'
                }}
              >
                <Box
                  sx={{
                    width: 16,
                    height: 16,
                    border: '2px solid rgba(255,255,255,0.3)',
                    borderTopColor: 'white',
                    borderRadius: '50%',
                    animation: 'spin 0.8s linear infinite',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' }
                    }
                  }}
                />
                <Typography variant="caption" sx={{ fontSize: '0.75rem' }}>
                  {t('audio.loading', 'Loading...')}
                </Typography>
              </Box>
            </Fade>
          )}

          {/* Visualizer Type Indicator */}
          {playing && !buffering && isReady && (
            <Fade in={showControls}>
              <Chip
                icon={<GraphicEq />}
                label={t('audio.visualizer_type', { count: visualizerType + 1, defaultValue: `Visualizer ${visualizerType + 1}` })}
                size="small"
                sx={{
                  position: 'absolute',
                  top: 16,
                  right: 16,
                  bgcolor: 'rgba(0, 0, 0, 0.6)',
                  color: 'white',
                  backdropFilter: 'blur(10px)'
                }}
              />
            </Fade>
          )}

          {/* Logo as Play/Pause Button */}
          <Box
            onClick={handlePlayPause}
            sx={{
              position: 'relative',
              cursor: 'pointer',
              opacity: showControls ? 1 : 0.3,
              transition: 'all 0.3s ease',
              '&:hover': {
                transform: 'scale(1.1)',
                opacity: 1
              },
              '&:active': {
                transform: 'scale(0.95)'
              },
              '& > *': {
                width: { xs: playing ? 80 : 120, md: playing ? 50 : 60 },
                height: { xs: playing ? 80 : 120, md: playing ? 50 : 60 }
              }
            }}
          >
            <Logo size={playing ? 80 : 120} />
            {/* Buffering overlay on logo */}
            {buffering && playing && (
              <Box
                sx={{
                  position: 'absolute',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  width: 40,
                  height: 40,
                  border: '3px solid rgba(255,255,255,0.3)',
                  borderTopColor: 'white',
                  borderRadius: '50%',
                  animation: 'spin 0.8s linear infinite'
                }}
              />
            )}
            {!playing && (
              <Box
                sx={{
                  position: 'absolute',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  width: '100%',
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  bgcolor: 'rgba(0, 0, 0, 0.3)',
                  borderRadius: '50%'
                }}
              >
                <PlayArrow sx={{ fontSize: { xs: 60, md: 40 }, color: 'white' }} />
              </Box>
            )}
            {playing && (
              <Box
                sx={{
                  position: 'absolute',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  width: '100%',
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  opacity: 0,
                  transition: 'opacity 0.2s',
                  '&:hover': {
                    opacity: 1,
                    bgcolor: 'rgba(0, 0, 0, 0.5)',
                    borderRadius: '50%'
                  }
                }}
              >
                <Pause sx={{ fontSize: { xs: 40, md: 30 }, color: 'white' }} />
              </Box>
            )}
          </Box>

          {/* Station Info */}
        <Box sx={{ textAlign: 'center' }}>
            <Typography 
              variant="h5" 
              fontWeight={600} 
              gutterBottom
              sx={{ 
                fontSize: { xs: '1.5rem', md: '1.1rem' },
                mb: { xs: 1, md: 0.5 },
                color: playing ? 'white' : 'text.primary',
                textShadow: playing ? '0 2px 10px rgba(0,0,0,0.5)' : 'none'
              }}
            >
              {station?.name || t('audio.select_station', 'Select a Station')}
            </Typography>
            {station?.genre && (
              <Typography 
                variant="body2" 
                sx={{ 
                  color: playing ? 'rgba(255,255,255,0.8)' : 'text.secondary',
                  textShadow: playing ? '0 1px 5px rgba(0,0,0,0.5)' : 'none'
                }}
              >
                {station.genre}
              </Typography>
            )}
          </Box>

          {/* Now Playing Metadata */}
          {metadata && playing && (metadata.title || metadata.artist || (metadata.song && !metadata.song.match(/^\w+_aacp?_\d+k?$/i))) && (
            <Fade in={true}>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: { xs: 1, md: 0.5 },
                  bgcolor: 'rgba(0, 0, 0, 0.6)',
                  backdropFilter: 'blur(10px)',
                  px: { xs: 3, md: 2 },
                  py: { xs: 1.5, md: 0.75 },
                  borderRadius: 3,
                  maxWidth: '90%'
                }}
              >
                <MusicNote sx={{ color: 'white', fontSize: { xs: 20, md: 16 } }} />
                <Box sx={{ textAlign: 'center' }}>
                  <Typography 
                    variant="body2" 
                    sx={{ 
                      color: 'white',
                      fontWeight: 600,
                      mb: { xs: 0.5, md: 0.25 },
                      fontSize: { xs: '0.875rem', md: '0.75rem' }
                    }}
                  >
                    {t('audio.now_playing', 'Now Playing')}
                  </Typography>
                  {metadata.title && (
                    <Typography 
                      variant="body1" 
                      sx={{ 
                        color: 'white',
                        fontWeight: 700,
                        fontSize: { xs: '1rem', md: '0.875rem' }
                      }}
                    >
                      {metadata.title}
                    </Typography>
                  )}
                  {metadata.artist && (
                    <Typography 
                      variant="body2" 
                      sx={{ 
                        color: 'rgba(255,255,255,0.8)',
                        fontSize: { xs: '0.875rem', md: '0.75rem' }
                      }}
                    >
                      {metadata.artist}
                    </Typography>
                  )}
                  {!metadata.title && !metadata.artist && metadata.streamTitle && (
                    <Typography 
                      variant="body2" 
                      sx={{ 
                        color: 'white'
                      }}
                    >
                      {metadata.streamTitle}
                    </Typography>
                  )}
                </Box>
              </Box>
            </Fade>
          )}

          {/* Casting Indicator */}
          {casting && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <CastConnected sx={{ color: 'white', fontSize: 20 }} />
              <Typography 
                variant="body2" 
                sx={{ 
                  color: 'white',
                  fontWeight: 600,
                  textShadow: '0 1px 5px rgba(0,0,0,0.5)'
                }}
              >
                {t('audio.casting', 'Casting to Device')}
              </Typography>
            </Box>
          )}
        </Box>

        {/* Navigation Controls */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <IconButton
            onClick={onPrevious}
            disabled={!onPrevious}
            sx={{ color: 'text.primary' }}
          >
            <SkipPrevious />
          </IconButton>

          <Box sx={{ width: 56 }} /> {/* Spacer where play button was */}

          <IconButton
            onClick={onNext}
            disabled={!onNext}
            sx={{ color: 'text.primary' }}
          >
            <SkipNext />
          </IconButton>
        </Box>

        {/* Volume Control */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, width: '100%', maxWidth: 300 }}>
          <IconButton size="small" onClick={handleToggleMute} sx={{ color: 'text.primary' }}>
            {muted ? <VolumeOff /> : <VolumeUp />}
          </IconButton>

          <Slider
            value={muted ? 0 : volume * 100}
            onChange={handleVolumeChange}
            sx={{ flex: 1 }}
          />

          {castAvailable && (
            <Tooltip title={casting ? 'Stop Casting' : 'Cast'}>
              <IconButton 
                size="small" 
                onClick={handleCast}
                sx={{ 
                  color: casting ? 'primary.main' : 'text.primary',
                  bgcolor: casting ? 'rgba(168, 85, 247, 0.1)' : 'transparent'
                }}
              >
                {casting ? <CastConnected /> : <Cast />}
              </IconButton>
            </Tooltip>
          )}
        </Box>

        {/* Live Indicator */}
        {playing && (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Box
              sx={{
                width: 8,
                height: 8,
                borderRadius: '50%',
                bgcolor: 'error.main',
                animation: 'blink 1.5s ease-in-out infinite',
                '@keyframes blink': {
                  '0%, 100%': { opacity: 1 },
                  '50%': { opacity: 0.3 }
                }
              }}
            />
            <Typography variant="caption" color="text.secondary" fontWeight={600}>
              LIVE
            </Typography>
          </Box>
        )}
      </Box>

      {/* Loading Indicator */}
      {playing && !isReady && (
        <LinearProgress sx={{ position: 'absolute', top: 0, left: 0, right: 0 }} />
      )}
    </Paper>
  );
}

export default AudioPlayer;
