import React, { useState, useMemo } from 'react';
import {
  Box,
  Drawer,
  Typography,
  IconButton,
  Divider,
  TextField,
  List,
  ListItem,
  ListItemButton,
  Tooltip,
  InputAdornment,
} from '@mui/material';
import {
  Menu as MenuIcon,
  Close as CloseIcon,
  Search as SearchIcon,
  CurrencyBitcoin,
} from '@mui/icons-material';

const DRAWER_WIDTH = 340;

// 암호화폐 목록 (주요 종목)
const CRYPTO_LIST = [
  { symbol: 'KRW-BTC', name: '비트코인', shortName: 'BTC', englishName: 'Bitcoin' },
  { symbol: 'KRW-ETH', name: '이더리움', shortName: 'ETH', englishName: 'Ethereum' },
  { symbol: 'KRW-XRP', name: '리플', shortName: 'XRP', englishName: 'Ripple' },
  { symbol: 'KRW-SOL', name: '솔라나', shortName: 'SOL', englishName: 'Solana' },
  { symbol: 'KRW-DOGE', name: '도지코인', shortName: 'DOGE', englishName: 'Dogecoin' },
  { symbol: 'KRW-ADA', name: '에이다', shortName: 'ADA', englishName: 'Cardano' },
  { symbol: 'KRW-AVAX', name: '아발란체', shortName: 'AVAX', englishName: 'Avalanche' },
  { symbol: 'KRW-DOT', name: '폴카닷', shortName: 'DOT', englishName: 'Polkadot' },
  { symbol: 'KRW-MATIC', name: '폴리곤', shortName: 'MATIC', englishName: 'Polygon' },
  { symbol: 'KRW-LINK', name: '체인링크', shortName: 'LINK', englishName: 'Chainlink' },
  { symbol: 'KRW-TRX', name: '트론', shortName: 'TRX', englishName: 'TRON' },
  { symbol: 'KRW-ATOM', name: '코스모스', shortName: 'ATOM', englishName: 'Cosmos' },
  { symbol: 'KRW-ETC', name: '이더리움클래식', shortName: 'ETC', englishName: 'Ethereum Classic' },
  { symbol: 'KRW-BCH', name: '비트코인캐시', shortName: 'BCH', englishName: 'Bitcoin Cash' },
  { symbol: 'KRW-SHIB', name: '시바이누', shortName: 'SHIB', englishName: 'Shiba Inu' },
  { symbol: 'KRW-APT', name: '앱토스', shortName: 'APT', englishName: 'Aptos' },
  { symbol: 'KRW-NEAR', name: '니어프로토콜', shortName: 'NEAR', englishName: 'NEAR Protocol' },
  { symbol: 'KRW-ARB', name: '아비트럼', shortName: 'ARB', englishName: 'Arbitrum' },
  { symbol: 'KRW-OP', name: '옵티미즘', shortName: 'OP', englishName: 'Optimism' },
  { symbol: 'KRW-SAND', name: '샌드박스', shortName: 'SAND', englishName: 'The Sandbox' },
  { symbol: 'KRW-MANA', name: '디센트럴랜드', shortName: 'MANA', englishName: 'Decentraland' },
  { symbol: 'KRW-AXS', name: '엑시인피니티', shortName: 'AXS', englishName: 'Axie Infinity' },
  { symbol: 'KRW-AAVE', name: '에이브', shortName: 'AAVE', englishName: 'Aave' },
  { symbol: 'KRW-EOS', name: '이오스', shortName: 'EOS', englishName: 'EOS' },
  { symbol: 'KRW-XLM', name: '스텔라루멘', shortName: 'XLM', englishName: 'Stellar Lumens' },
  { symbol: 'KRW-HBAR', name: '헤데라', shortName: 'HBAR', englishName: 'Hedera' },
  { symbol: 'KRW-ALGO', name: '알고랜드', shortName: 'ALGO', englishName: 'Algorand' },
  { symbol: 'KRW-VET', name: '비체인', shortName: 'VET', englishName: 'VeChain' },
  { symbol: 'KRW-THETA', name: '세타토큰', shortName: 'THETA', englishName: 'THETA' },
  { symbol: 'KRW-FTM', name: '팬텀', shortName: 'FTM', englishName: 'Fantom' },
  { symbol: 'KRW-1INCH', name: '1인치네트워크', shortName: '1INCH', englishName: '1inch Network' },
  { symbol: 'KRW-GAS', name: '가스', shortName: 'GAS', englishName: 'GAS' },
];

interface CryptoListPanelProps {
  currentSymbol: string;
  onSelectSymbol: (symbol: string) => void;
}

const CryptoListPanel: React.FC<CryptoListPanelProps> = ({
  currentSymbol,
  onSelectSymbol,
}) => {
  const [open, setOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const handleToggle = () => {
    setOpen(!open);
  };

  const handleSelect = (symbol: string) => {
    onSelectSymbol(symbol);
    setOpen(false);
  };

  // 검색 필터링
  const filteredList = useMemo(() => {
    if (!searchQuery) return CRYPTO_LIST;
    const query = searchQuery.toLowerCase();
    return CRYPTO_LIST.filter(
      crypto =>
        crypto.name.toLowerCase().includes(query) ||
        crypto.shortName.toLowerCase().includes(query) ||
        crypto.symbol.toLowerCase().includes(query)
    );
  }, [searchQuery]);

  return (
    <>
      {/* Floating Icon Button - 좌측 하단 */}
      <Tooltip title="종목 선택" placement="right">
        <IconButton
          onClick={handleToggle}
          sx={{
            position: 'fixed',
            bottom: 24,
            left: 24,
            zIndex: 1200,
            color: 'white',
            '&:hover': {
              bgcolor: 'rgba(255, 255, 255, 0.1)',
            },
          }}
        >
          <MenuIcon sx={{ fontSize: 28 }} />
        </IconButton>
      </Tooltip>

      {/* Crypto List Drawer */}
      <Drawer
        anchor="left"
        open={open}
        onClose={handleToggle}
        sx={{
          '& .MuiDrawer-paper': {
            width: DRAWER_WIDTH,
            boxSizing: 'border-box',
          },
        }}
      >
        {/* Header */}
        <Box
          sx={{
            p: 2,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            bgcolor: 'primary.main',
            color: 'primary.contrastText',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <CurrencyBitcoin />
            <Typography variant="h6" fontWeight="bold">
              종목 선택
            </Typography>
          </Box>
          <IconButton onClick={handleToggle} sx={{ color: 'inherit' }}>
            <CloseIcon />
          </IconButton>
        </Box>

        {/* Search */}
        <Box sx={{ p: 2 }}>
          <TextField
            fullWidth
            size="small"
            placeholder="종목명 또는 심볼 검색..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon color="action" />
                </InputAdornment>
              ),
            }}
            sx={{
              '& .MuiOutlinedInput-root': {
                borderRadius: 2,
              },
            }}
          />
        </Box>

        <Divider />

        {/* Crypto List */}
        <Box sx={{ flexGrow: 1, overflow: 'auto' }}>
          <List disablePadding>
            {filteredList.map((crypto, index) => {
              const isSelected = currentSymbol === crypto.symbol;

              return (
                <React.Fragment key={crypto.symbol}>
                  <ListItem disablePadding>
                    <ListItemButton
                      selected={isSelected}
                      onClick={() => handleSelect(crypto.symbol)}
                      sx={{
                        py: 1.5,
                        px: 2,
                        '&.Mui-selected': {
                          bgcolor: 'action.selected',
                          '&:hover': {
                            bgcolor: 'action.selected',
                          },
                        },
                      }}
                    >
                      <Box sx={{ 
                        display: 'flex', 
                        alignItems: 'center', 
                        justifyContent: 'space-between',
                        width: '100%',
                      }}>
                        {/* 왼쪽: 한글명 + 영문명 */}
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <Typography 
                            variant="body1" 
                            fontWeight="bold"
                          >
                            {crypto.name}
                          </Typography>
                          <Typography 
                            variant="body2" 
                            color="text.secondary"
                          >
                            {crypto.englishName}
                          </Typography>
                        </Box>
                        {/* 오른쪽: 주식코드 */}
                        <Typography 
                          variant="body2" 
                          sx={{
                            color: 'primary.light',
                            fontWeight: 500,
                            fontSize: 12,
                          }}
                        >
                          {crypto.symbol}
                        </Typography>
                      </Box>
                    </ListItemButton>
                  </ListItem>
                  {index < filteredList.length - 1 && <Divider />}
                </React.Fragment>
              );
            })}
          </List>
        </Box>

        {/* Footer */}
        <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography variant="caption" color="text.secondary">
            총 {filteredList.length}개 종목
          </Typography>
          <IconButton 
            onClick={handleToggle} 
            size="small"
            sx={{ 
              color: 'text.secondary',
              '&:hover': {
                color: 'primary.main',
              },
            }}
          >
            <CloseIcon fontSize="small" />
          </IconButton>
        </Box>
      </Drawer>
    </>
  );
};

export default CryptoListPanel;

