import React, { useState, useEffect, useRef } from 'react';
import { Box, Grid, Typography, Chip, CircularProgress, Card, CardMedia, CardContent, Button, IconButton, Menu, MenuItem, ListItemIcon, ListItemText, Dialog, DialogTitle, DialogContent, DialogActions, DialogContentText } from '@mui/material';
import { Add, Refresh, Edit, Favorite, FavoriteBorder, Star, StarBorder, Delete } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';
import axios from 'axios';
import { getProxiedLogoUrl } from '../utils/api';
import { useAuthStore } from '../store/authStore';
import AudioPlayer from '../components/AudioPlayer';
import Logo from '../components/Logo';
import ChannelLogoManager from '../components/ChannelLogoManager';
import { showChannelNotification, requestNotificationPermission } from '../utils/notifications';

const Radio = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const { token } = useAuthStore();
  const playerRef = useRef(null);
  const [channels, setChannels] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedChannel, setSelectedChannel] = useState(null);
  const [filter, setFilter] = useState('all');
  const [logoManagerOpen, setLogoManagerOpen] = useState(false);
  const [channelToEdit, setChannelToEdit] = useState(null);
  const [favorites, setFavorites] = useState(new Set());
  const [contextMenu, setContextMenu] = useState(null);
  const [contextChannel, setContextChannel] = useState(null);
  const [longPressTimer, setLongPressTimer] = useState(null);
  const [nowPlaying, setNowPlaying] = useState(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [channelToDelete, setChannelToDelete] = useState(null);
  const metadataIntervalRef = useRef(null);

  useEffect(() => {
    if (token) {
      fetchChannels();
      fetchFavorites();
      // Request notification permission
      requestNotificationPermission();
    }
    
    // Cleanup polling on unmount
    return () => {
      if (metadataIntervalRef.current) {
        clearInterval(metadataIntervalRef.current);
      }
    };
  }, [token]);

  // Poll for now playing metadata when channel is selected
  useEffect(() => {
    // Clear previous interval
    if (metadataIntervalRef.current) {
      clearInterval(metadataIntervalRef.current);
    }
    
    if (selectedChannel) {
      // Fetch immediately
      fetchNowPlaying(selectedChannel.id);
      
      // Then poll every 10 seconds
      metadataIntervalRef.current = setInterval(() => {
        fetchNowPlaying(selectedChannel.id);
      }, 10000);
    } else {
      setNowPlaying(null);
    }
    
    return () => {
      if (metadataIntervalRef.current) {
        clearInterval(metadataIntervalRef.current);
      }
    };
  }, [selectedChannel]);

  const fetchNowPlaying = async (channelId) => {
    try {
      const response = await axios.get(`/api/metadata/radio/${channelId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setNowPlaying(response.data);
    } catch (error) {
      // Silently fail - metadata might not be available for all streams
      console.debug('Metadata fetch failed:', error);
    }
  };

  const fetchFavorites = async () => {
    try {
      const response = await axios.get('/api/favorites?isRadio=true', {
        headers: { Authorization: `Bearer ${token}` }
      });
      const favIds = new Set(response.data.map(fav => fav.id));
      setFavorites(favIds);
    } catch (error) {
      console.error('Failed to fetch favorites:', error);
    }
  };

  const handleToggleFavorite = async (channelId, event) => {
    if (event) event.stopPropagation();
    const isFavorite = favorites.has(channelId);

    try {
      if (isFavorite) {
        await axios.delete(`/api/favorites/${channelId}`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        setFavorites(prev => {
          const newSet = new Set(prev);
          newSet.delete(channelId);
          return newSet;
        });
      } else {
        await axios.post(`/api/favorites/${channelId}`, {}, {
          headers: { Authorization: `Bearer ${token}` }
        });
        setFavorites(prev => new Set([...prev, channelId]));
      }
    } catch (error) {
      console.error('Failed to toggle favorite:', error);
    }
  };

  const handleContextMenu = (event, channel) => {
    event.preventDefault();
    setContextMenu({
      mouseX: event.clientX - 2,
      mouseY: event.clientY - 4,
    });
    setContextChannel(channel);
  };

  const handleCloseContextMenu = () => {
    setContextMenu(null);
    setContextChannel(null);
  };

  const handleContextFavorite = () => {
    if (contextChannel) {
      handleToggleFavorite(contextChannel.id, null);
    }
    handleCloseContextMenu();
  };

  const handleDeleteChannel = async () => {
    if (!channelToDelete) return;

    try {
      await axios.delete(`/api/channels/${channelToDelete.id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      // Remove from channels list
      setChannels(prev => prev.filter(ch => ch.id !== channelToDelete.id));
      
      // Remove from favorites if present
      setFavorites(prev => {
        const newSet = new Set(prev);
        newSet.delete(channelToDelete.id);
        return newSet;
      });

      // Clear selected channel if it was deleted
      if (selectedChannel?.id === channelToDelete.id) {
        setSelectedChannel(channels.find(ch => ch.id !== channelToDelete.id) || null);
      }

      setDeleteDialogOpen(false);
      setChannelToDelete(null);
    } catch (error) {
      console.error('Failed to delete channel:', error);
      alert('Failed to delete channel. Please try again.');
    }
  };

  const handleContextDelete = () => {
    if (contextChannel) {
      setChannelToDelete(contextChannel);
      setDeleteDialogOpen(true);
    }
    handleCloseContextMenu();
  };

  const handleLongPressStart = (channel) => {
    const timer = setTimeout(() => {
      if (navigator.vibrate) {
        navigator.vibrate(50);
      }
      setContextChannel(channel);
      setContextMenu({ mouseX: 0, mouseY: 0 });
    }, 500);
    setLongPressTimer(timer);
  };

  const handleLongPressEnd = () => {
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      setLongPressTimer(null);
    }
  };

  // Handle auto-play from search
  useEffect(() => {
    if (location.state?.autoPlayChannel && channels.length > 0) {
      const channel = channels.find(ch => ch.id === location.state.autoPlayChannel.id);
      if (channel) {
        setSelectedChannel(channel);
        // Show notification for now playing
        showChannelNotification(channel, 'radio');
        // Scroll to player
        setTimeout(() => {
          playerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
      }
      // Clear the state
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location.state, channels, navigate, location.pathname]);

  // Handle group selection from search
  useEffect(() => {
    if (location.state?.selectedGroup) {
      setFilter(location.state.selectedGroup);
      // Clear the state
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location.state, navigate, location.pathname]);

  const fetchChannels = async () => {
    try {
      const response = await axios.get('/api/channels?isRadio=true', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setChannels(response.data);
      if (response.data.length > 0 && !selectedChannel) {
        setSelectedChannel(response.data[0]);
      }
    } catch (error) {
      console.error('Failed to fetch radio channels:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleFilterChange = (newFilter) => {
    setFilter(newFilter);
  };

  const filteredChannels = channels.filter((channel) => {
    if (filter === 'all') return true;
    return channel.group_name?.toLowerCase().includes(filter.toLowerCase());
  });

  const handleChannelClick = (channel) => {
    setSelectedChannel(channel);
    // Show notification for now playing
    showChannelNotification(channel, 'radio');
    // Auto-scroll to player after brief delay for state update
    setTimeout(() => {
      playerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 100);
  };

  const handleChannelSelect = (channel) => {
    if (channel) {
      handleChannelClick(channel);
    }
  };

  const getNextChannel = () => {
    if (!selectedChannel || filteredChannels.length === 0) return null;
    const currentIndex = filteredChannels.findIndex(ch => ch.id === selectedChannel.id);
    const nextIndex = (currentIndex + 1) % filteredChannels.length;
    return filteredChannels[nextIndex];
  };

  const getPreviousChannel = () => {
    if (!selectedChannel || filteredChannels.length === 0) return null;
    const currentIndex = filteredChannels.findIndex(ch => ch.id === selectedChannel.id);
    const previousIndex = currentIndex === 0 ? filteredChannels.length - 1 : currentIndex - 1;
    return filteredChannels[previousIndex];
  };

  const handleLogoEdit = (channel, event) => {
    event.stopPropagation();
    setChannelToEdit(channel);
    setLogoManagerOpen(true);
  };

  const handleLogoUpdated = (updatedChannel) => {
    setChannels(channels.map(ch => 
      ch.id === updatedChannel.id ? updatedChannel : ch
    ));
    if (selectedChannel?.id === updatedChannel.id) {
      setSelectedChannel(updatedChannel);
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress size={32} />
      </Box>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h5" fontWeight="bold">
          {t('radio')}
        </Typography>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <IconButton size="small" onClick={fetchChannels}>
            <Refresh fontSize="small" />
          </IconButton>
          <Button 
            size="small" 
            variant="contained" 
            startIcon={<Add />}
            onClick={() => navigate('/settings')}
          >
            {t('add_playlist')}
          </Button>
        </Box>
      </Box>

      {selectedChannel && (
        <Box ref={playerRef} sx={{ mb: 2, scrollMarginTop: '20px', position: 'relative' }}>
          <AudioPlayer 
            station={selectedChannel} 
            onNext={() => handleChannelSelect(getNextChannel())} 
            onPrevious={() => handleChannelSelect(getPreviousChannel())} 
          />
          {/* Favorite Star Button for Playing Channel */}
          <IconButton
            onClick={() => handleToggleFavorite(selectedChannel.id, null)}
            sx={{
              position: 'absolute',
              top: 16,
              right: 16,
              zIndex: 10,
              bgcolor: 'rgba(0, 0, 0, 0.7)',
              color: favorites.has(selectedChannel.id) ? 'warning.main' : 'white',
              '&:hover': {
                bgcolor: 'rgba(0, 0, 0, 0.9)',
                transform: 'scale(1.1)'
              },
              transition: 'all 0.2s'
            }}
          >
            {favorites.has(selectedChannel.id) ? (
              <Star fontSize="large" />
            ) : (
              <StarBorder fontSize="large" />
            )}
          </IconButton>
          
          {/* Now Playing Information */}
          {nowPlaying && (nowPlaying.song || nowPlaying.artist || nowPlaying.title) && (
            <Box 
              sx={{ 
                mt: 2, 
                p: 2, 
                bgcolor: 'background.paper',
                borderRadius: 1,
                border: '1px solid',
                borderColor: 'divider'
              }}
            >
              <Typography variant="overline" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
                {t('now_playing')}
              </Typography>
              {nowPlaying.artist && nowPlaying.title ? (
                <>
                  <Typography variant="h6" fontWeight="bold">
                    {nowPlaying.title}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    {nowPlaying.artist}
                  </Typography>
                </>
              ) : (
                <Typography variant="h6" fontWeight="bold">
                  {nowPlaying.song}
                </Typography>
              )}
              {(nowPlaying.genre || nowPlaying.bitrate) && (
                <Box sx={{ display: 'flex', gap: 1, mt: 1, flexWrap: 'wrap' }}>
                  {nowPlaying.genre && (
                    <Chip label={nowPlaying.genre} size="small" variant="outlined" />
                  )}
                  {nowPlaying.bitrate && (
                    <Chip label={nowPlaying.bitrate} size="small" variant="outlined" />
                  )}
                </Box>
              )}
            </Box>
          )}
        </Box>
      )}

      <Box sx={{ mb: 2, display: 'flex', gap: 0.75, flexWrap: 'wrap' }}>
        {['all', 'music', 'news', 'talk', 'sports'].map((filterOption) => (
          <Chip
            key={filterOption}
            label={t(filterOption) || filterOption}
            size="small"
            onClick={() => handleFilterChange(filterOption)}
            color={filter === filterOption ? 'primary' : 'default'}
            sx={{ textTransform: 'capitalize', fontSize: '0.75rem' }}
          />
        ))}
      </Box>

      <Grid container spacing={1.5}>
        {filteredChannels.map((channel) => (
          <Grid item xs={6} sm={4} md={3} lg={2} key={channel.id}>
            <Card
              sx={{
                cursor: 'pointer',
                transition: 'transform 0.2s, box-shadow 0.2s',
                position: 'relative',
                '&:hover': {
                  transform: 'translateY(-2px)',
                  boxShadow: 4
                },
                '&:hover .logo-edit-btn': {
                  opacity: 1
                },
                border: selectedChannel?.id === channel.id ? 2 : 0,
                borderColor: 'primary.main'
              }}
              onClick={() => handleChannelClick(channel)}
              onContextMenu={(e) => handleContextMenu(e, channel)}
              onTouchStart={() => handleLongPressStart(channel)}
              onTouchEnd={handleLongPressEnd}
              onTouchMove={handleLongPressEnd}
              onMouseDown={() => handleLongPressStart(channel)}
              onMouseUp={handleLongPressEnd}
              onMouseLeave={handleLongPressEnd}
            >
              {/* Favorite Button */}
              <IconButton
                size="small"
                onClick={(e) => handleToggleFavorite(channel.id, e)}
                sx={{
                  position: 'absolute',
                  top: 4,
                  left: 4,
                  zIndex: 1,
                  bgcolor: 'rgba(0,0,0,0.6)',
                  color: favorites.has(channel.id) ? 'error.main' : 'white',
                  '&:hover': { bgcolor: 'rgba(0,0,0,0.8)' }
                }}
              >
                {favorites.has(channel.id) ? (
                  <Favorite fontSize="small" />
                ) : (
                  <FavoriteBorder fontSize="small" />
                )}
              </IconButton>

              <IconButton
                className="logo-edit-btn"
                size="small"
                onClick={(e) => handleLogoEdit(channel, e)}
                sx={{
                  position: 'absolute',
                  top: 4,
                  right: 4,
                  zIndex: 1,
                  bgcolor: 'rgba(0,0,0,0.6)',
                  color: 'white',
                  opacity: 0,
                  transition: 'opacity 0.2s',
                  '&:hover': { bgcolor: 'rgba(0,0,0,0.8)' }
                }}
              >
                <Edit fontSize="small" />
              </IconButton>

              {channel.logo ? (
                <CardMedia
                  component="img"
                  height="100"
                  image={getProxiedLogoUrl(channel.logo)}
                  alt={channel.name}
                  crossOrigin="anonymous"
                  sx={{ objectFit: 'contain', bgcolor: 'background.default', p: 1 }}
                  onError={(e) => {
                    console.log(`[Logo] Failed to load: ${channel.logo}`);
                    e.target.style.display = 'none';
                    e.target.nextSibling.style.display = 'flex';
                  }}
                />
              ) : null}
              <Box
                sx={{
                  height: 100,
                  display: channel.logo ? 'none' : 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  bgcolor: 'background.default'
                }}
              >
                <Logo size={56} />
              </Box>
              <CardContent sx={{ p: 1, '&:last-child': { pb: 1 } }}>
                <Typography variant="caption" fontWeight="600" noWrap display="block">
                  {channel.name}
                </Typography>
                <Typography variant="caption" color="text.secondary" noWrap display="block" fontSize="0.7rem">
                  {channel.group_name || 'Radio'}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>

      {filteredChannels.length === 0 && (
        <Box sx={{ textAlign: 'center', py: 6 }}>
          <Typography variant="body1" color="text.secondary" gutterBottom>
            {t('no_channels')}
          </Typography>
          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={() => navigate('/settings')}
            sx={{ mt: 2 }}
          >
            {t('add_playlist')}
          </Button>
        </Box>
      )}

      <ChannelLogoManager
        open={logoManagerOpen}
        onClose={() => {
          setLogoManagerOpen(false);
          setChannelToEdit(null);
        }}
        channel={channelToEdit}
        onLogoUpdated={handleLogoUpdated}
      />

      {/* Context Menu for Favorites */}
      <Menu
        open={contextMenu !== null}
        onClose={handleCloseContextMenu}
        anchorReference="anchorPosition"
        anchorPosition={
          contextMenu !== null
            ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
            : undefined
        }
      >
        <MenuItem onClick={handleContextFavorite}>
          <ListItemIcon>
            {contextChannel && favorites.has(contextChannel.id) ? (
              <Favorite fontSize="small" color="error" />
            ) : (
              <FavoriteBorder fontSize="small" />
            )}
          </ListItemIcon>
          <ListItemText>
            {contextChannel && favorites.has(contextChannel.id)
              ? 'Remove from Favorites'
              : 'Add to Favorites'}
          </ListItemText>
        </MenuItem>
        <MenuItem onClick={handleContextDelete}>
          <ListItemIcon>
            <Delete fontSize="small" color="error" />
          </ListItemIcon>
          <ListItemText>Delete Channel</ListItemText>
        </MenuItem>
      </Menu>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>Delete Channel</DialogTitle>
        <DialogContent>
          <DialogContentText>
            Are you sure you want to delete <strong>{channelToDelete?.name}</strong>? This action cannot be undone.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>Cancel</Button>
          <Button onClick={handleDeleteChannel} color="error" variant="contained">
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Radio;
