import React, { useRef, useState, useEffect } from 'react';
import { Box, Paper, IconButton, Typography, Slider, Tooltip } from '@mui/material';
import {
  PlayArrow,
  Pause,
  VolumeUp,
  VolumeOff,
  Fullscreen,
  FiberManualRecord,
  PictureInPicture,
  PictureInPictureAlt,
  Cast,
  CastConnected
} from '@mui/icons-material';
import ReactPlayer from 'react-player';
import Logo from './Logo';
import { useAuthStore } from '../store/authStore';
import { useChromecast } from '../utils/useChromecast';

function VideoPlayer({ channel, enablePip = true }) {
  const playerRef = useRef(null);
  const videoElementRef = useRef(null);
  const { token } = useAuthStore();
  const [playing, setPlaying] = useState(false);
  const [volume, setVolume] = useState(0.8);
  const [muted, setMuted] = useState(false);
  const [pip, setPip] = useState(false);
  const [isReady, setIsReady] = useState(false);
  const [pipSupported, setPipSupported] = useState(false);
  const [showLogo, setShowLogo] = useState(true);
  const hideLogoTimer = useRef(null);
  
  // Chromecast support
  const { 
    castAvailable, 
    casting, 
    castMedia, 
    stopCasting, 
    openCastDialog,
    setCastVolume,
    setCastMuted
  } = useChromecast();

  // Auto-hide logo after 2 seconds
  const resetLogoTimer = () => {
    setShowLogo(true);
    if (hideLogoTimer.current) {
      clearTimeout(hideLogoTimer.current);
    }
    if (playing) {
      hideLogoTimer.current = setTimeout(() => {
        setShowLogo(false);
      }, 2000);
    }
  };

  // Show logo on mouse move
  const handleMouseMove = () => {
    if (playing) {
      resetLogoTimer();
    }
  };

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



  // Reset timer when playing changes
  useEffect(() => {
    if (playing) {
      resetLogoTimer();
    } else {
      setShowLogo(true);
      if (hideLogoTimer.current) {
        clearTimeout(hideLogoTimer.current);
      }
    }
  }, [playing]);

  // Check PiP support on mount
  useEffect(() => {
    if (document.pictureInPictureEnabled) {
      setPipSupported(true);
    }
  }, []);

  // Listen for PiP events
  useEffect(() => {
    const handlePipEnter = () => setPip(true);
    const handlePipExit = () => setPip(false);

    if (videoElementRef.current) {
      videoElementRef.current.addEventListener('enterpictureinpicture', handlePipEnter);
      videoElementRef.current.addEventListener('leavepictureinpicture', handlePipExit);
    }

    return () => {
      if (videoElementRef.current) {
        videoElementRef.current.removeEventListener('enterpictureinpicture', handlePipEnter);
        videoElementRef.current.removeEventListener('leavepictureinpicture', handlePipExit);
      }
    };
  }, [videoElementRef.current]);

  // Always use proxy to bypass geo-blocking and CORS
  const getStreamUrl = () => {
    if (!channel?.id) return '';
    // Use backend proxy for ALL streams to handle CORS and geo-blocking
    return `/api/stream/proxy/${channel.id}?token=${token}`;
  };

  // Get full URL for Chromecast (needs absolute URL)
  const getFullStreamUrl = () => {
    const streamUrl = getStreamUrl();
    if (!streamUrl) return '';
    // Convert relative URL to absolute
    return `${window.location.origin}${streamUrl}`;
  };

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

  // Handle Chromecast
  const handleCast = async () => {
    if (casting) {
      // Stop casting
      stopCasting();
      // Resume local playback
      setPlaying(false);
    } else {
      // Start casting
      if (!channel) return;
      
      // Pause local playback
      setPlaying(false);
      
      // Try to get original URL first (Chromecast can access it directly)
      const originalUrl = await getOriginalChannelUrl();
      const castUrl = originalUrl || getFullStreamUrl();
      
      console.log('[Cast] Casting URL:', castUrl);
      console.log('[Cast] Channel:', channel.name);
      console.log('[Cast] Is Radio:', channel.is_radio === 1);
      
      // Cast the media
      const success = await castMedia({
        url: castUrl,
        title: channel.name || 'TV Channel',
        subtitle: channel.is_radio === 1 ? 'Radio Station' : 'Live TV',
        contentType: 'application/x-mpegURL',
        imageUrl: channel.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]);

  // For radio, use native audio element instead of ReactPlayer
  if (channel?.is_radio === 1) {
    return (
      <Paper
        sx={{
          position: 'relative',
          width: '100%',
          aspectRatio: '16/9',
          bgcolor: 'black',
          borderRadius: 3,
          overflow: 'hidden'
        }}
      >
        {/* Audio Player for Radio */}
        <Box
          sx={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.15) 0%, rgba(59, 130, 246, 0.15) 100%)',
            gap: 2
          }}
        >
          <Logo size={120} />
          <Typography variant="h6" sx={{ color: 'white', fontWeight: 600 }}>
            {channel?.name || 'Radio Station'}
          </Typography>
          
          <audio
            controls
            autoPlay={playing}
            src={getStreamUrl()}
            style={{ width: '80%', maxWidth: '400px' }}
            onPlay={() => setPlaying(true)}
            onPause={() => setPlaying(false)}
            onError={(e) => {
              console.error('Radio playback error:', e);
              setPlaying(false);
            }}
          />
        </Box>
      </Paper>
    );
  }

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

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

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

  const handleFullscreen = () => {
    const player = playerRef.current?.wrapper;
    if (player) {
      if (player.requestFullscreen) {
        player.requestFullscreen();
      }
    }
  };

  const handlePip = async () => {
    if (!pipSupported || !enablePip) return;

    try {
      const videoElement = playerRef.current?.getInternalPlayer();
      
      if (!videoElement) {
        console.warn('Video element not found for PiP');
        return;
      }

      if (document.pictureInPictureElement) {
        // Exit PiP
        await document.exitPictureInPicture();
        setPip(false);
      } else {
        // Enter PiP
        await videoElement.requestPictureInPicture();
        setPip(true);
      }
    } catch (error) {
      console.error('PiP error:', error);
    }
  };

  // Store video element reference when player is ready
  const handleReady = () => {
    setIsReady(true);
    const internalPlayer = playerRef.current?.getInternalPlayer();
    if (internalPlayer) {
      videoElementRef.current = internalPlayer;
    }
  };

  return (
    <Paper
      onMouseMove={handleMouseMove}
      onTouchStart={handleMouseMove}
      sx={{
        position: 'relative',
        width: '100%',
        aspectRatio: '16/9',
        bgcolor: 'black',
        borderRadius: 3,
        overflow: 'hidden'
      }}
    >
      {/* Hide player when casting */}
      {!casting && (
        <ReactPlayer
          ref={playerRef}
          url={getStreamUrl()}
          playing={playing}
          volume={volume}
          muted={muted}
          width="100%"
          height="100%"
          style={{ position: 'absolute', top: 0, left: 0 }}
          onReady={handleReady}
          onError={(error) => {
            console.error('Video playback error:', error);
            setPlaying(false);
            setIsReady(false);
          }}
          config={{
            file: {
              attributes: {
                crossOrigin: 'anonymous',
                disablePictureInPicture: !enablePip
              },
              forceHLS: true,
              hlsOptions: {
                xhrSetup: function(xhr, url) {
                  xhr.withCredentials = false;
                }
              }
            }
          }}
        />
      )}

      {/* Casting indicator */}
      {casting && (
        <Box
          sx={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.2) 0%, rgba(59, 130, 246, 0.2) 100%)',
            gap: 3
          }}
        >
          <CastConnected sx={{ fontSize: 120, color: 'primary.main', opacity: 0.8 }} />
          <Typography variant="h5" sx={{ color: 'white', fontWeight: 600 }}>
            Casting to TV
          </Typography>
          <Typography variant="body1" sx={{ color: 'white', opacity: 0.7 }}>
            {channel?.name || 'TV Channel'}
          </Typography>
        </Box>
      )}

      {/* Center Logo Play/Pause Button - Auto-hide when playing */}
      <Box
        onClick={handlePlayPause}
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          gap: 2,
          cursor: 'pointer',
          zIndex: 10,
          opacity: showLogo ? 1 : 0,
          pointerEvents: showLogo ? 'auto' : 'none',
          transition: 'opacity 0.3s ease, transform 0.3s ease',
          '&:hover': {
            transform: 'translate(-50%, -50%) scale(1.1)'
          },
          '&:active': {
            transform: 'translate(-50%, -50%) scale(0.95)'
          }
        }}
      >
        <Box
          sx={{
            position: 'relative',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <Logo size={playing ? 80 : 120} />
          {!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.5)',
                borderRadius: '50%'
              }}
            >
              <PlayArrow sx={{ fontSize: 60, color: 'white' }} />
            </Box>
          )}
        </Box>
        {!playing && (
          <Typography variant="h6" sx={{ color: 'white', fontWeight: 600, textAlign: 'center' }}>
            {channel?.name || 'Ready to Play'}
          </Typography>
        )}
      </Box>

      {/* Semi-transparent overlay when not playing */}
      {!playing && (
        <Box
          sx={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.15) 0%, rgba(59, 130, 246, 0.15) 100%)',
            zIndex: 5
          }}
        />
      )}

      <Box
        sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          background: 'linear-gradient(180deg, rgba(0,0,0,0.7) 0%, transparent 100%)',
          p: 2,
          display: 'flex',
          alignItems: 'center',
          gap: 1
        }}
      >
        <FiberManualRecord sx={{ color: 'red', fontSize: 16 }} />
        <Typography variant="body2" sx={{ color: 'white', fontWeight: 600 }}>
          {channel?.name}
        </Typography>
        <Box sx={{ ml: 'auto' }}>
          <IconButton size="small" sx={{ color: 'white', bgcolor: 'rgba(255,255,255,0.1)' }}>
            <FiberManualRecord fontSize="small" />
          </IconButton>
        </Box>
      </Box>

      <Box
        sx={{
          position: 'absolute',
          bottom: 0,
          left: 0,
          right: 0,
          background: 'linear-gradient(0deg, rgba(0,0,0,0.7) 0%, transparent 100%)',
          p: 2
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <IconButton onClick={handleToggleMute} sx={{ color: 'white' }}>
            {muted ? <VolumeOff /> : <VolumeUp />}
          </IconButton>

          <Slider
            value={muted ? 0 : volume * 100}
            onChange={handleVolumeChange}
            sx={{ width: 100, color: 'white' }}
          />

          <Box sx={{ flexGrow: 1 }} />

          {castAvailable && (
            <Tooltip title={casting ? 'Stop Casting' : 'Cast'}>
              <IconButton 
                onClick={handleCast} 
                sx={{ 
                  color: 'white',
                  bgcolor: casting ? 'rgba(168, 85, 247, 0.3)' : 'transparent'
                }}
              >
                {casting ? <CastConnected /> : <Cast />}
              </IconButton>
            </Tooltip>
          )}

          {pipSupported && enablePip && (
            <Tooltip title={pip ? 'Exit Picture-in-Picture' : 'Picture-in-Picture'}>
              <IconButton 
                onClick={handlePip} 
                sx={{ 
                  color: 'white',
                  bgcolor: pip ? 'rgba(168, 85, 247, 0.3)' : 'transparent'
                }}
              >
                {pip ? <PictureInPictureAlt /> : <PictureInPicture />}
              </IconButton>
            </Tooltip>
          )}

          <Tooltip title="Fullscreen">
            <IconButton onClick={handleFullscreen} sx={{ color: 'white' }}>
              <Fullscreen />
            </IconButton>
          </Tooltip>
        </Box>
      </Box>
    </Paper>
  );
}

export default VideoPlayer;
