import React, { useState, useEffect } from 'react';
import {
  Box,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  TextField,
  InputAdornment,
  Typography,
  CircularProgress,
  Divider,
} from '@mui/material';
import {
  NotificationsActive,
  NotificationsOff,
  Search as SearchIcon,
} from '@mui/icons-material';
import { upbitApiService } from '../../services/upbitApi';
import { getAllAlerts, createAlert, toggleAlert, CryptoAlertDto } from '../../services/alertApi';

interface CryptoInfo {
  symbol: string;
  koreanName: string;
  englishName: string;
}

interface CryptoListPanelProps {
  onSelectCrypto: (crypto: CryptoInfo, alertId?: number) => void;
  selectedSymbol?: string;
  onDoubleClickCrypto?: (crypto: CryptoInfo) => void;
}

/**
 * 암호화폐 목록 패널
 */
const CryptoListPanel: React.FC<CryptoListPanelProps> = ({ onSelectCrypto, selectedSymbol, onDoubleClickCrypto }) => {
  const [cryptoList, setCryptoList] = useState<CryptoInfo[]>([]);
  const [alerts, setAlerts] = useState<CryptoAlertDto[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadCryptos();
    loadAlerts();
  }, []);

  // 투자분석 화면에서 알림 토글 시 목록 동기화
  useEffect(() => {
    const handleCryptoAlertChanged = () => {
      loadAlerts();
    };
    window.addEventListener('cryptoAlertChanged', handleCryptoAlertChanged);
    return () => window.removeEventListener('cryptoAlertChanged', handleCryptoAlertChanged);
  }, []);

  const loadCryptos = async () => {
    try {
      setLoading(true);
      const markets = await upbitApiService.getMarkets();
      const cryptos = markets.map(m => ({
        symbol: m.market,
        koreanName: m.korean_name,
        englishName: m.english_name,
      }));
      setCryptoList(cryptos);
    } catch (error) {
      console.error('암호화폐 목록 로드 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadAlerts = async () => {
    try {
      const alertList = await getAllAlerts();
      setAlerts(alertList);
    } catch (error) {
      console.error('알림 목록 로드 실패:', error);
    }
  };

  const getAlertForSymbol = (symbol: string): CryptoAlertDto | undefined => {
    return alerts.find(a => a.symbol === symbol);
  };

  const isAlertEnabled = (symbol: string): boolean => {
    const alert = getAlertForSymbol(symbol);
    return alert?.enabled || false;
  };

  const handleToggleAlert = async (crypto: CryptoInfo) => {
    try {
      const existingAlert = getAlertForSymbol(crypto.symbol);
      
      if (existingAlert) {
        // 기존 알림이 있으면 토글
        const updated = await toggleAlert(existingAlert.id!, !existingAlert.enabled);
        setAlerts(prev => prev.map(a => a.id === updated.id ? updated : a));
        
        // 투자분석 화면과 동기화: cryptoAlertChanged 이벤트 dispatch
        window.dispatchEvent(new CustomEvent('cryptoAlertChanged', { detail: { symbol: crypto.symbol } }));
        
        // 활성화되면 해당 암호화폐 선택
        if (updated.enabled) {
          onSelectCrypto(crypto, updated.id);
        }
      } else {
        // 새로운 알림 생성
        const newAlert: CryptoAlertDto = {
          symbol: crypto.symbol,
          koreanName: crypto.koreanName,
          englishName: crypto.englishName,
          enabled: true,
        };
        const created = await createAlert(newAlert);
        setAlerts(prev => [...prev, created]);
        
        // 투자분석 화면과 동기화: cryptoAlertChanged 이벤트 dispatch
        window.dispatchEvent(new CustomEvent('cryptoAlertChanged', { detail: { symbol: crypto.symbol } }));
        
        // 새로 생성된 암호화폐 선택
        onSelectCrypto(crypto, created.id);
      }
    } catch (error) {
      console.error('알림 토글 실패:', error);
      alert('알림 설정에 실패했습니다.');
    }
  };

  const handleCryptoClick = (crypto: CryptoInfo) => {
    const alert = getAlertForSymbol(crypto.symbol);
    if (alert && alert.enabled) {
      onSelectCrypto(crypto, alert.id);
    }
  };

  // 검색 필터링 및 정렬 (활성화된 알림이 상단에)
  const filteredCryptos = cryptoList
    .filter(crypto => {
      const query = searchQuery.toLowerCase();
      return (
        crypto.koreanName.toLowerCase().includes(query) ||
        crypto.englishName.toLowerCase().includes(query) ||
        crypto.symbol.toLowerCase().includes(query)
      );
    })
    .sort((a, b) => {
      const aEnabled = isAlertEnabled(a.symbol);
      const bEnabled = isAlertEnabled(b.symbol);
      
      // 활성화된 알림이 먼저 오도록 정렬
      if (aEnabled && !bEnabled) return -1;
      if (!aEnabled && bEnabled) return 1;
      
      // 같은 상태면 한글 이름으로 정렬
      return a.koreanName.localeCompare(b.koreanName, 'ko');
    });

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

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Search */}
      <TextField
        fullWidth
        size="small"
        placeholder="암호화폐 검색..."
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <SearchIcon />
            </InputAdornment>
          ),
        }}
        sx={{ mb: 2 }}
      />

      {/* List */}
      <Box sx={{ flexGrow: 1, overflow: 'auto' }}>
        {/* 활성화된 알림 개수 표시 */}
        <Typography variant="caption" color="text.secondary" sx={{ mb: 1, display: 'block', px: 2 }}>
          활성화된 알림: {alerts.filter(a => a.enabled).length}개
        </Typography>
        
        <List dense>
          {filteredCryptos.map((crypto, index) => {
            const enabled = isAlertEnabled(crypto.symbol);
            const isSelected = crypto.symbol === selectedSymbol;
            const prevEnabled = index > 0 ? isAlertEnabled(filteredCryptos[index - 1].symbol) : true;
            const isLastItem = index === filteredCryptos.length - 1;
            
            // 활성화/비활성화 구분선
            const showSectionDivider = index > 0 && prevEnabled && !enabled;
            
            return (
              <React.Fragment key={crypto.symbol}>
                {showSectionDivider && (
                  <Box sx={{ px: 2, py: 1 }}>
                    <Typography variant="caption" color="text.secondary">
                      ─── 비활성화된 종목 ───
                    </Typography>
                  </Box>
                )}
                <ListItem
                  button
                  selected={isSelected}
                  onClick={() => handleCryptoClick(crypto)}
                  onDoubleClick={() => onDoubleClickCrypto?.(crypto)}
                  sx={{
                    borderRadius: 1,
                    backgroundColor: enabled ? 'rgba(255, 193, 7, 0.08)' : 'transparent',
                    '&.Mui-selected': {
                      backgroundColor: 'action.selected',
                    },
                    '&:hover': {
                      backgroundColor: enabled ? 'rgba(255, 193, 7, 0.15)' : 'action.hover',
                    },
                  }}
                >
                  <ListItemText
                    primary={crypto.koreanName}
                    secondary={
                      <Typography variant="caption" color="text.secondary">
                        {crypto.englishName}
                      </Typography>
                    }
                  />
                  <ListItemSecondaryAction>
                    <IconButton
                      edge="end"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleToggleAlert(crypto);
                      }}
                      sx={{
                        color: enabled ? 'warning.main' : 'action.disabled',
                      }}
                    >
                      {enabled ? <NotificationsActive /> : <NotificationsOff />}
                    </IconButton>
                  </ListItemSecondaryAction>
                </ListItem>
                {!isLastItem && <Divider sx={{ my: 0.5 }} />}
              </React.Fragment>
            );
          })}
        </List>
      </Box>
    </Box>
  );
};

export default CryptoListPanel;

