import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  CircularProgress, 
  Card, 
  CardMedia, 
  CardContent, 
  Grid, 
  IconButton, 
  Chip,
  Alert
} from '@mui/material';
import { PlayArrow, Delete, Favorite as FavoriteIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import { useAuthStore } from '../store/authStore';
import Logo from '../components/Logo';

const Favorites = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { type = 'tv' } = useParams(); // tv or radio
  const { token } = useAuthStore();
  const [favorites, setFavorites] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchFavorites();
  }, [type]);

  const fetchFavorites = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`/api/favorites?isRadio=${type === 'radio'}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setFavorites(response.data);
    } catch (error) {
      console.error('Failed to fetch favorites:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRemoveFavorite = async (channelId) => {
    try {
      await axios.delete(`/api/favorites/${channelId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setFavorites(favorites.filter(fav => fav.id !== channelId));
    } catch (error) {
      console.error('Failed to remove favorite:', error);
    }
  };

  const handlePlay = (channel) => {
    if (type === 'radio') {
      navigate('/radio', { state: { autoPlayChannel: channel } });
    } else {
      navigate('/live-tv', { state: { autoPlayChannel: channel } });
    }
  };

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

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
        <FavoriteIcon sx={{ color: 'primary.main', fontSize: 32 }} />
        <Typography variant="h5" fontWeight="bold">
          {type === 'radio' ? t('favorite_radio') : t('favorite_tv')}
        </Typography>
        <Chip 
          label={`${favorites.length} ${favorites.length === 1 ? 'channel' : 'channels'}`} 
          size="small"
          color="primary"
        />
      </Box>

      {favorites.length === 0 ? (
        <Alert severity="info" sx={{ borderRadius: 2 }}>
          No favorite {type === 'radio' ? 'radio stations' : 'TV channels'} yet. 
          Start adding channels to your favorites from the {type === 'radio' ? 'Radio' : 'Live TV'} page!
        </Alert>
      ) : (
        <Grid container spacing={2}>
          {favorites.map((channel) => (
            <Grid item xs={12} sm={6} md={4} lg={3} key={channel.id}>
              <Card 
                sx={{ 
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  position: 'relative',
                  transition: 'transform 0.2s, box-shadow 0.2s',
                  '&:hover': {
                    transform: 'translateY(-4px)',
                    boxShadow: 4
                  }
                }}
              >
                {/* Remove Favorite Button */}
                <IconButton
                  size="small"
                  onClick={() => handleRemoveFavorite(channel.id)}
                  sx={{
                    position: 'absolute',
                    top: 8,
                    right: 8,
                    bgcolor: 'rgba(0, 0, 0, 0.6)',
                    color: 'error.main',
                    zIndex: 1,
                    '&:hover': {
                      bgcolor: 'rgba(0, 0, 0, 0.8)'
                    }
                  }}
                >
                  <Delete fontSize="small" />
                </IconButton>

                <CardMedia
                  sx={{
                    height: 140,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    bgcolor: 'action.hover',
                    position: 'relative'
                  }}
                >
                  {channel.logo ? (
                    <img
                      src={channel.logo.startsWith('http') ? channel.logo : `/logos/${channel.logo}`}
                      alt={channel.name}
                      style={{ maxWidth: '80%', maxHeight: '80%', objectFit: 'contain' }}
                    />
                  ) : (
                    <Logo size={60} />
                  )}
                </CardMedia>

                <CardContent sx={{ flexGrow: 1, pb: 1 }}>
                  <Typography 
                    variant="subtitle2" 
                    fontWeight="bold" 
                    noWrap 
                    title={channel.name}
                  >
                    {channel.name}
                  </Typography>
                  <Typography variant="caption" color="text.secondary" noWrap>
                    {channel.group_name || 'No Category'}
                  </Typography>
                </CardContent>

                <Box sx={{ p: 1, pt: 0, textAlign: 'center' }}>
                  <IconButton
                    onClick={() => handlePlay(channel)}
                    sx={{
                      bgcolor: 'primary.main',
                      color: 'white',
                      '&:hover': {
                        bgcolor: 'primary.dark'
                      },
                      width: '100%',
                      borderRadius: 1
                    }}
                  >
                    <PlayArrow />
                  </IconButton>
                </Box>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}
    </Box>
  );
};

export default Favorites;

