import React, { useState, useEffect } from 'react';
import {
  Box,
  Drawer,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  IconButton,
  Typography,
  Divider,
} from '@mui/material';
import {
  Star as StarIcon,
  Close as CloseIcon,
  Delete as DeleteIcon,
} from '@mui/icons-material';
import { getAllFavorites, removeFavorite, CryptoFavoriteDto } from '../services/cryptoFavoriteApi';

interface FavoritesPanelProps {
  open: boolean;
  onClose: () => void;
  onSelectSymbol: (symbol: string) => void;
  currentSymbol?: string;
}

/**
 * 즐겨찾기 패널 컴포넌트
 */
const FavoritesPanel: React.FC<FavoritesPanelProps> = ({
  open,
  onClose,
  onSelectSymbol,
  currentSymbol,
}) => {
  const [favorites, setFavorites] = useState<CryptoFavoriteDto[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (open) {
      loadFavorites();
    }
  }, [open]);

  const loadFavorites = async () => {
    try {
      setLoading(true);
      const data = await getAllFavorites();
      setFavorites(data);
    } catch (error) {
      console.error('즐겨찾기 로드 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRemoveFavorite = async (e: React.MouseEvent, symbol: string) => {
    e.stopPropagation(); // 이벤트 버블링 방지
    e.preventDefault();
    try {
      console.log('즐겨찾기 삭제 시도:', symbol);
      await removeFavorite(symbol);
      console.log('즐겨찾기 삭제 성공:', symbol);
      // 삭제 후 목록 새로고침
      await loadFavorites();
    } catch (error) {
      console.error('즐겨찾기 삭제 실패:', error);
    }
  };

  const handleSelectFavorite = (symbol: string) => {
    onSelectSymbol(symbol);
    onClose();
  };

  return (
    <Drawer
      anchor="left"
      open={open}
      onClose={onClose}
      sx={{
        '& .MuiDrawer-paper': {
          width: 280,
          bgcolor: 'background.paper',
          color: 'text.primary',
          borderRight: 1,
          borderColor: 'divider',
        },
      }}
    >
      <Box sx={{ p: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between', bgcolor: 'background.default' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <StarIcon sx={{ color: '#fbbf24' }} />
          <Typography variant="h6" fontWeight="bold">
            즐겨찾기
          </Typography>
        </Box>
        <IconButton onClick={onClose} size="small">
          <CloseIcon />
        </IconButton>
      </Box>
      
      <Divider />

      <Box sx={{ flex: 1, overflow: 'auto' }}>
        {loading ? (
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Typography color="text.secondary">로딩 중...</Typography>
          </Box>
        ) : favorites.length === 0 ? (
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Typography color="text.secondary">
              즐겨찾기가 비어있습니다.
              <br />
              종목 선택 드롭다운에서 ⭐를 눌러
              <br />
              즐겨찾기에 추가하세요.
            </Typography>
          </Box>
        ) : (
          <List dense>
            {favorites.map((fav) => (
              <ListItem
                key={fav.symbol}
                disablePadding
                sx={{
                  position: 'relative', // absolute 포지셔닝을 위한 기준점
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                }}
              >
                <ListItemButton
                  selected={currentSymbol === fav.symbol}
                  onClick={() => handleSelectFavorite(fav.symbol)}
                  sx={{
                    pr: 6, // 우측 여백 확보 (삭제 버튼 공간)
                    '&:hover': {
                      bgcolor: 'action.hover',
                    },
                    '&.Mui-selected': {
                      bgcolor: 'action.selected',
                      '&:hover': {
                        bgcolor: 'action.selected',
                      },
                    },
                  }}
                >
                  <ListItemText
                    primary={fav.koreanName}
                    secondary={fav.symbol.replace('KRW-', '')}
                    primaryTypographyProps={{
                      fontSize: '14px',
                      fontWeight: currentSymbol === fav.symbol ? 600 : 400,
                    }}
                    secondaryTypographyProps={{
                      fontSize: '12px',
                    }}
                  />
                </ListItemButton>
                {/* 삭제 버튼 - 명시적으로 배치 */}
                <IconButton
                  size="small"
                  onClick={(e) => handleRemoveFavorite(e, fav.symbol)}
                  sx={{ 
                    position: 'absolute',
                    right: 8,
                    color: '#ef4444',
                    '&:hover': {
                      bgcolor: 'rgba(239, 68, 68, 0.1)',
                    },
                  }}
                  title="즐겨찾기에서 삭제"
                >
                  <DeleteIcon fontSize="small" />
                </IconButton>
              </ListItem>
            ))}
          </List>
        )}
      </Box>
    </Drawer>
  );
};

export default FavoritesPanel;
