/**
 * 투자분석 컨트롤 패널
 * - 종목 선택
 * - 시간봉 선택
 * - 전략 선택
 * - 설정 버튼
 * 
 * React.memo로 최적화
 */

import React from 'react';
import {
  Box,
  Paper,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Tooltip,
  Button,
  Chip,
  Typography,
} from '@mui/material';
import {
  Settings as SettingsIcon,
  Refresh,
  Fullscreen,
  FullscreenExit,
  Notifications as NotificationsIcon,
  NotificationsOff as NotificationsOffIcon,
} from '@mui/icons-material';
import CryptoNameComboBox from '../CryptoNameComboBox';

export interface ControlPanelProps {
  // 현재 상태
  symbol: string;
  timeInterval: string;
  uptrendStrategyId: number | null;
  downtrendStrategyId: number | null;
  generalStrategyId: number | null;
  alertEnabled: boolean;
  isFullscreen: boolean;
  realtimePrice: number | null;
  
  // 옵션 목록
  strategyRules: Array<{ id: number; name: string }>;
  
  // 이벤트 핸들러
  onSymbolChange: (symbol: string) => void;
  onTimeIntervalChange: (interval: string) => void;
  onUptrendStrategyChange: (id: number | null) => void;
  onDowntrendStrategyChange: (id: number | null) => void;
  onGeneralStrategyChange: (id: number | null) => void;
  onAlertToggle: () => void;
  onRefresh: () => void;
  onFullscreenToggle: () => void;
  onSettingsOpen: () => void;
  
  // 로딩 상태
  loading?: boolean;
  alertLoading?: boolean;
}

const ControlPanel: React.FC<ControlPanelProps> = (props) => {
  const {
    symbol,
    timeInterval,
    uptrendStrategyId,
    downtrendStrategyId,
    generalStrategyId,
    alertEnabled,
    isFullscreen,
    realtimePrice,
    strategyRules,
    onSymbolChange,
    onTimeIntervalChange,
    onUptrendStrategyChange,
    onDowntrendStrategyChange,
    onGeneralStrategyChange,
    onAlertToggle,
    onRefresh,
    onFullscreenToggle,
    onSettingsOpen,
    loading = false,
    alertLoading = false,
  } = props;

  console.log(`🎛️ [ControlPanel] 렌더링`);

  return (
    <Paper
      elevation={2}
      sx={{
        p: 2,
        mb: 2,
        bgcolor: 'background.paper',
      }}
    >
      <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
        {/* 종목 선택 */}
        <Box sx={{ minWidth: 200 }}>
          <CryptoNameComboBox
            value={symbol}
            onChange={onSymbolChange}
            disabled={loading}
          />
        </Box>

        {/* 시간봉 선택 */}
        <FormControl size="small" sx={{ minWidth: 120 }}>
          <InputLabel>시간봉</InputLabel>
          <Select
            value={timeInterval}
            label="시간봉"
            onChange={(e) => onTimeIntervalChange(e.target.value)}
            disabled={loading}
          >
            <MenuItem value="1m">1분</MenuItem>
            <MenuItem value="3m">3분</MenuItem>
            <MenuItem value="5m">5분</MenuItem>
            <MenuItem value="15m">15분</MenuItem>
            <MenuItem value="30m">30분</MenuItem>
            <MenuItem value="1h">1시간</MenuItem>
            <MenuItem value="4h">4시간</MenuItem>
            <MenuItem value="1d">일봉</MenuItem>
            <MenuItem value="1w">주봉</MenuItem>
            <MenuItem value="1M">월봉</MenuItem>
          </Select>
        </FormControl>

        {/* 상승 전략 */}
        <FormControl size="small" sx={{ minWidth: 150 }}>
          <InputLabel>상승 전략</InputLabel>
          <Select
            value={uptrendStrategyId || ''}
            label="상승 전략"
            onChange={(e) => onUptrendStrategyChange(e.target.value ? Number(e.target.value) : null)}
            disabled={loading}
          >
            <MenuItem value="">없음</MenuItem>
            {strategyRules.map((rule) => (
              <MenuItem key={rule.id} value={rule.id}>
                {rule.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        {/* 하락 전략 */}
        <FormControl size="small" sx={{ minWidth: 150 }}>
          <InputLabel>하락 전략</InputLabel>
          <Select
            value={downtrendStrategyId || ''}
            label="하락 전략"
            onChange={(e) => onDowntrendStrategyChange(e.target.value ? Number(e.target.value) : null)}
            disabled={loading}
          >
            <MenuItem value="">없음</MenuItem>
            {strategyRules.map((rule) => (
              <MenuItem key={rule.id} value={rule.id}>
                {rule.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        {/* 일반 전략 */}
        <FormControl size="small" sx={{ minWidth: 150 }}>
          <InputLabel>일반 전략</InputLabel>
          <Select
            value={generalStrategyId || ''}
            label="일반 전략"
            onChange={(e) => onGeneralStrategyChange(e.target.value ? Number(e.target.value) : null)}
            disabled={loading}
          >
            <MenuItem value="">없음</MenuItem>
            {strategyRules.map((rule) => (
              <MenuItem key={rule.id} value={rule.id}>
                {rule.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        {/* 구분선 */}
        <Box sx={{ flexGrow: 1 }} />

        {/* 실시간 가격 */}
        {realtimePrice && (
          <Chip
            label={`₩ ${realtimePrice.toLocaleString()}`}
            color="primary"
            size="small"
          />
        )}

        {/* 알림 토글 */}
        <Tooltip title={alertEnabled ? '알림 끄기' : '알림 켜기'}>
          <span>
            <IconButton
              onClick={onAlertToggle}
              disabled={alertLoading}
              color={alertEnabled ? 'primary' : 'default'}
            >
              {alertEnabled ? <NotificationsIcon /> : <NotificationsOffIcon />}
            </IconButton>
          </span>
        </Tooltip>

        {/* 새로고침 */}
        <Tooltip title="새로고침">
          <span>
            <IconButton onClick={onRefresh} disabled={loading}>
              <Refresh />
            </IconButton>
          </span>
        </Tooltip>

        {/* 전체화면 */}
        <Tooltip title={isFullscreen ? '전체화면 해제' : '전체화면'}>
          <IconButton onClick={onFullscreenToggle}>
            {isFullscreen ? <FullscreenExit /> : <Fullscreen />}
          </IconButton>
        </Tooltip>

        {/* 설정 */}
        <Tooltip title="설정">
          <IconButton onClick={onSettingsOpen}>
            <SettingsIcon />
          </IconButton>
        </Tooltip>
      </Box>
    </Paper>
  );
};

export default React.memo(ControlPanel, (prevProps, nextProps) => {
  return (
    prevProps.symbol === nextProps.symbol &&
    prevProps.timeInterval === nextProps.timeInterval &&
    prevProps.uptrendStrategyId === nextProps.uptrendStrategyId &&
    prevProps.downtrendStrategyId === nextProps.downtrendStrategyId &&
    prevProps.generalStrategyId === nextProps.generalStrategyId &&
    prevProps.alertEnabled === nextProps.alertEnabled &&
    prevProps.isFullscreen === nextProps.isFullscreen &&
    prevProps.realtimePrice === nextProps.realtimePrice &&
    prevProps.loading === nextProps.loading &&
    prevProps.alertLoading === nextProps.alertLoading &&
    prevProps.strategyRules === nextProps.strategyRules
  );
});
