import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Select,
  MenuItem,
  FormControl,
  CircularProgress,
  Alert,
  Drawer,
  Button,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Switch,
  Chip,
  Paper,
} from '@mui/material';
import {
  Refresh as RefreshIcon,
  Settings as SettingsIcon,
  Menu as MenuIcon,
  Fullscreen,
  FullscreenExit,
  Search as SearchIcon,
  Tune as TuneIcon,
  Visibility,
  VisibilityOff,
  DragIndicator,
  Brightness4,
  Brightness7,
  ZoomIn,
  ZoomOut,
  RestartAlt,
} from '@mui/icons-material';
import { Time } from 'lightweight-charts';
import { useUpbitData } from '../contexts/UpbitDataContext';
import { useAppTheme } from '../contexts/ThemeContext';
import CandlestickChart, { ChartHandle } from '../components/CandlestickChart';
import IndicatorChart from '../components/IndicatorChart';
import CryptoNameComboBox from '../components/CryptoNameComboBox';
import ChartToolbar, { ChartTool } from '../components/ChartToolbar';
import { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import { useIndicatorSettings } from '../contexts/IndicatorSettingsContext';
import { useChartColors } from '../contexts/ChartColorContext';
import MASettingsDialog from '../components/MASettingsDialog';
import IchimokuSettingsDialog from '../components/IchimokuSettingsDialog';
import BollingerSettingsDialog from '../components/BollingerSettingsDialog';
import IndicatorParamsSettingsDialog from '../components/IndicatorParamsSettingsDialog';

/**
 * 모바일 전용 차트 페이지 (완전 재구현 버전)
 * 
 * 주요 기능:
 * 1. 화면에 fit한 레이아웃 - 캔들차트 + 보조지표가 화면을 완전히 채움
 * 2. 동적 높이 조절 - 보조지표 추가/제거 시 자동으로 높이 재계산
 * 3. 리사이저 - 캔들차트 하단을 드래그하여 비율 조절 (30-80%)
 * 4. 동기화된 스크롤 - 모든 차트가 동시에 좌우 스크롤
 * 5. 크로스헤어 동기화 - 터치 시 모든 차트에 크로스헤어 표시
 * 6. 터치 최적화 - 가로 드래그=스크롤, 핀치=줌
 */
const MobileChartPage: React.FC = () => {
  // ============================================================================
  // 1. Contexts & Hooks
  // ============================================================================
  const {
    symbol,
    setSymbol,
    timeInterval,
    setTimeInterval,
    macdData,
    loading,
    error,
    fetchChartData,
  } = useUpbitData();

  const { settings: indicatorVisibilitySettings, updateSettings: updateIndicatorSettings } = useIndicatorVisibility();
  const { indicatorSettings: paramSettings } = useIndicatorSettings();
  const { colors: colorSettings } = useChartColors();
  const { themeMode, setThemeMode } = useAppTheme();

  // ============================================================================
  // 2. Refs
  // ============================================================================
  const chartRef = useRef<ChartHandle>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // ============================================================================
  // 3. UI States
  // ============================================================================
  const [showSettings, setShowSettings] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // Settings Dialogs
  const [maSettingsOpen, setMaSettingsOpen] = useState(false);
  const [ichimokuSettingsOpen, setIchimokuSettingsOpen] = useState(false);
  const [bollingerSettingsOpen, setBollingerSettingsOpen] = useState(false);
  const [indicatorParamsOpen, setIndicatorParamsOpen] = useState(false);

  // ============================================================================
  // 4. Layout States
  // ============================================================================
  const [candleChartHeightRatio, setCandleChartHeightRatio] = useState(0.6); // 캔들차트 60%, 보조지표 40%
  const [isResizing, setIsResizing] = useState(false);

  // ============================================================================
  // 5. Chart Synchronization States
  // ============================================================================
  const [sharedTimeRange, setSharedTimeRange] = useState<{ from: number; to: number } | null>(null);
  const [sharedHoverTime, setSharedHoverTime] = useState<Time | null>(null);
  const syncThrottleTimer = useRef<NodeJS.Timeout | null>(null);

  // ============================================================================
  // 6. Data Transformation (macdData → candleData, indicatorData)
  // ============================================================================
  const candleData = useMemo(() => {
    if (!macdData || macdData.length === 0) return [];

    return macdData.map((item) => ({
      time: item.timestamp || item.date,
      open: item.open || item.close,
      high: item.high || item.close,
      low: item.low || item.close,
      close: item.close,
      volume: item.volume || 0,
    }));
  }, [macdData]);

  const indicatorData = useMemo(() => {
    if (!macdData || macdData.length === 0) return [];

    return macdData.map((item) => ({
      time: item.timestamp || item.date,
      timestamp: item.timestamp || item.date,
      open: item.open,
      high: item.high,
      low: item.low,
      close: item.close,
      volume: item.volume,
      macdLine: item.macdLine ?? undefined,
      macdSignal: item.signalLine ?? undefined,
      macdHistogram: item.macdHistogram ?? undefined,
      rsi: item.rsi ?? undefined,
      stochasticK: item.stochasticK ?? undefined,
      stochasticD: item.stochasticD ?? undefined,
      cci: item.cci ?? undefined,
      adx: item.adx ?? undefined,
      obv: item.obv ?? undefined,
      psychologicalLine: item.newPsychological ?? undefined,
      plusDI: item.plusDI ?? undefined,
      minusDI: item.minusDI ?? undefined,
    }));
  }, [macdData]);

  // ============================================================================
  // 7. Active Indicators Calculation
  // ============================================================================
  const activeIndicators = useMemo(() => {
    const indicators: Array<{
      key: string;
      type: string;
      label: string;
      isActive: boolean;
    }> = [
      { key: 'volume', type: 'volume', label: '거래량', isActive: indicatorVisibilitySettings.volume },
      {
        key: 'macd',
        type: 'macd',
        label: 'MACD',
        isActive: indicatorVisibilitySettings.macdLine || indicatorVisibilitySettings.macdHistogram,
      },
      { key: 'rsi', type: 'rsi', label: 'RSI', isActive: indicatorVisibilitySettings.rsi },
      {
        key: 'stochastic',
        type: 'stochastic',
        label: 'Stochastic',
        isActive: indicatorVisibilitySettings.stochasticSlow,
      },
      { key: 'cci', type: 'cci', label: 'CCI', isActive: indicatorVisibilitySettings.cci },
      { key: 'adx', type: 'adx', label: 'ADX', isActive: indicatorVisibilitySettings.adx },
      { key: 'obv', type: 'obv', label: 'OBV', isActive: indicatorVisibilitySettings.obv },
      {
        key: 'newPsychological',
        type: 'newPsychological',
        label: '신심리도',
        isActive: indicatorVisibilitySettings.newPsychological,
      },
      {
        key: 'investPsychological',
        type: 'investPsychological',
        label: '투자심리도',
        isActive: indicatorVisibilitySettings.investPsychological,
      },
    ];

    return indicators.filter((ind) => ind.isActive);
  }, [indicatorVisibilitySettings]);

  // ============================================================================
  // 8. Layout Calculation
  // ============================================================================
  const layoutMetrics = useMemo(() => {
    const APPBAR_HEIGHT = 56;
    const TOOLBAR_HEIGHT = 44; // 하단 툴바 (종목 선택, 시간 간격 등) - 더 작게
    const RESIZER_HEIGHT = 6; // 리사이저 더 얇게
    const INDICATOR_TITLE_HEIGHT = 24; // 타이틀 더 작게
    const MIN_CANDLE_HEIGHT = 280;
    const MIN_INDICATOR_HEIGHT = 70;

    // 사용 가능한 전체 높이
    const availableHeight = Math.max(
      500,
      window.innerHeight - APPBAR_HEIGHT - TOOLBAR_HEIGHT
    );

    // 캔들 차트 높이
    const candleHeight = Math.max(
      MIN_CANDLE_HEIGHT,
      Math.floor(availableHeight * candleChartHeightRatio)
    );

    // 보조지표 영역 전체 높이
    const indicatorAreaHeight = Math.max(
      0,
      availableHeight - candleHeight - (activeIndicators.length > 0 ? RESIZER_HEIGHT : 0)
    );

    // 각 보조지표 높이 (타이틀 포함)
    const singleIndicatorHeight =
      activeIndicators.length > 0
        ? Math.max(MIN_INDICATOR_HEIGHT, Math.floor(indicatorAreaHeight / activeIndicators.length))
        : 0;

    // 차트 영역 높이 (타이틀 제외)
    const chartHeight = Math.max(50, singleIndicatorHeight - INDICATOR_TITLE_HEIGHT);

    console.log('📐 [MobileChartV2] Layout Metrics:', {
      availableHeight,
      candleHeight,
      candleChartHeightRatio,
      indicatorAreaHeight,
      activeIndicatorCount: activeIndicators.length,
      singleIndicatorHeight,
      chartHeight,
    });

    return {
      APPBAR_HEIGHT,
      TOOLBAR_HEIGHT,
      RESIZER_HEIGHT,
      INDICATOR_TITLE_HEIGHT,
      availableHeight,
      candleHeight,
      indicatorAreaHeight,
      singleIndicatorHeight,
      chartHeight,
    };
  }, [candleChartHeightRatio, activeIndicators.length]);

  // ============================================================================
  // 9. Chart Synchronization Handlers
  // ============================================================================
  
  // ✅ 시간 범위 변경 시 throttle 적용 (성능 최적화)
  const handleVisibleRangeChange = useCallback((from: number, to: number) => {
    if (syncThrottleTimer.current) {
      clearTimeout(syncThrottleTimer.current);
    }

    syncThrottleTimer.current = setTimeout(() => {
      setSharedTimeRange({ from, to });
    }, 100); // 100ms throttle
  }, []);

  // ✅ 크로스헤어 이동 시 모든 차트에 적용
  const handleCrosshairMove = useCallback((time: Time | null) => {
    setSharedHoverTime(time);
  }, []);

  // ============================================================================
  // 10. Resizer Handler (캔들/보조지표 비율 조절)
  // ============================================================================
  const handleResizerMouseDown = (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault();
    setIsResizing(true);

    const startY = 'touches' in e ? e.touches[0].clientY : e.clientY;
    const startRatio = candleChartHeightRatio;

    const handleMove = (moveEvent: MouseEvent | TouchEvent) => {
      const currentY = 'touches' in moveEvent ? moveEvent.touches[0].clientY : moveEvent.clientY;
      const deltaY = currentY - startY;
      const deltaRatio = deltaY / layoutMetrics.availableHeight;
      let newRatio = startRatio + deltaRatio;

      // 최소/최대 비율 제한 (캔들: 30-80%, 보조지표: 20-70%)
      newRatio = Math.max(0.3, Math.min(0.8, newRatio));

      setCandleChartHeightRatio(newRatio);
    };

    const handleEnd = () => {
      setIsResizing(false);
      document.removeEventListener('mousemove', handleMove);
      document.removeEventListener('mouseup', handleEnd);
      document.removeEventListener('touchmove', handleMove);
      document.removeEventListener('touchend', handleEnd);
    };

    document.addEventListener('mousemove', handleMove);
    document.addEventListener('mouseup', handleEnd);
    document.addEventListener('touchmove', handleMove);
    document.addEventListener('touchend', handleEnd);
  };

  // ============================================================================
  // 11. Chart Control Handlers (차트 버튼은 차트 내부에서 처리)
  // ============================================================================
  // Note: 줌/리셋 버튼은 CandlestickChart 컴포넌트 내부에 구현되어 있음

  const handleRefresh = () => {
    fetchChartData(symbol, timeInterval);
  };

  const toggleTheme = () => {
    setThemeMode(themeMode === 'dark' ? 'light' : 'dark');
  };

  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  // ============================================================================
  // 12. Indicator Toggle Handler
  // ============================================================================
  const handleIndicatorToggle = (indicatorKey: keyof typeof indicatorVisibilitySettings) => {
    updateIndicatorSettings({
      [indicatorKey]: !indicatorVisibilitySettings[indicatorKey],
    });
  };

  // ============================================================================
  // 13. Render
  // ============================================================================
  return (
    <Box
      ref={containerRef}
      sx={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        bgcolor: 'background.default',
      }}
    >
      {/* ======================================================================== */}
      {/* AppBar (상단 네비게이션) */}
      {/* ======================================================================== */}
      {!isFullscreen && (
        <AppBar position="static" elevation={1}>
          <Toolbar sx={{ minHeight: '56px !important', px: 1 }}>
            <IconButton edge="start" color="inherit" onClick={() => setShowSettings(true)}>
              <MenuIcon />
            </IconButton>

            <Typography variant="h6" sx={{ flexGrow: 1, ml: 1, fontSize: '1rem' }}>
              차트
            </Typography>

            <IconButton color="inherit" onClick={toggleTheme} size="small">
              {themeMode === 'dark' ? <Brightness7 /> : <Brightness4 />}
            </IconButton>

            <IconButton color="inherit" onClick={handleRefresh} size="small">
              <RefreshIcon />
            </IconButton>

            <IconButton color="inherit" onClick={toggleFullscreen} size="small">
              {isFullscreen ? <FullscreenExit /> : <Fullscreen />}
            </IconButton>
          </Toolbar>
        </AppBar>
      )}

      {/* ======================================================================== */}
      {/* 차트 영역 */}
      {/* ======================================================================== */}
      <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {loading && candleData.length === 0 ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', flex: 1 }}>
            <CircularProgress />
          </Box>
        ) : error ? (
          <Box sx={{ p: 2 }}>
            <Alert severity="error">{error}</Alert>
          </Box>
        ) : candleData.length > 0 ? (
          <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* ============================================================ */}
            {/* 캔들스틱 차트 */}
            {/* ============================================================ */}
            <Box
              sx={{
                height: `${layoutMetrics.candleHeight}px`,
                position: 'relative',
                flex: 'none',
              }}
            >
              <CandlestickChart
                ref={chartRef}
                data={candleData}
                indicatorData={indicatorData}
                height={layoutMetrics.candleHeight}
                showLeftButton={false}
                showRightButton={false}
                onTimeRangeChange={() => {}}
                onCrosshairMove={handleCrosshairMove}
                onVisibleRangeChange={handleVisibleRangeChange}
                onNavigate={() => {}}
                externalHoverTime={sharedHoverTime}
                isMobileMode={true}
                sharedTimeRange={sharedTimeRange}
                indicatorSettings={paramSettings}
                colorSettings={colorSettings}
                activeTool={null}
              />

              {/* Note: 모바일에서는 차트 툴바를 숨김 (심플한 UI) */}
            </Box>

            {/* ============================================================ */}
            {/* 리사이저 (드래그 핸들) */}
            {/* ============================================================ */}
            {!isFullscreen && activeIndicators.length > 0 && (
              <Box
                onMouseDown={handleResizerMouseDown}
                onTouchStart={handleResizerMouseDown}
                sx={{
                  height: `${layoutMetrics.RESIZER_HEIGHT}px`,
                  bgcolor: isResizing ? 'primary.main' : 'divider',
                  cursor: 'ns-resize',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  userSelect: 'none',
                  transition: 'background-color 0.2s',
                  '&:hover': {
                    bgcolor: 'primary.light',
                  },
                  '&:active': {
                    bgcolor: 'primary.main',
                  },
                }}
              >
                <DragIndicator sx={{ color: 'text.secondary', fontSize: 20 }} />
              </Box>
            )}

            {/* ============================================================ */}
            {/* 보조지표 차트들 */}
            {/* ============================================================ */}
            {activeIndicators.length > 0 && (
              <Box
                sx={{
                  flex: 1,
                  display: 'flex',
                  flexDirection: 'column',
                  overflow: 'hidden',
                }}
              >
                {activeIndicators.map((indicator, index) => (
                  <Box
                    key={indicator.key}
                    sx={{
                      height: `${layoutMetrics.singleIndicatorHeight}px`,
                      flex: 'none',
                      display: 'flex',
                      flexDirection: 'column',
                    }}
                  >
                    {/* 보조지표 타이틀 (간소화) */}
                    <Box
                      sx={{
                        height: `${layoutMetrics.INDICATOR_TITLE_HEIGHT}px`,
                        px: 1,
                        display: 'flex',
                        alignItems: 'center',
                        bgcolor: 'background.paper',
                        borderBottom: 1,
                        borderColor: 'divider',
                      }}
                    >
                      <Typography variant="caption" fontWeight="bold" sx={{ fontSize: '0.7rem' }}>
                        {indicator.label}
                      </Typography>
                    </Box>

                    {/* 보조지표 차트 */}
                    <Box sx={{ flex: 1, minHeight: 0 }}>
                      <IndicatorChart
                        type={indicator.type as any}
                        data={indicatorData}
                        height={layoutMetrics.chartHeight}
                        title=""
                        onCrosshairMove={handleCrosshairMove}
                        onVisibleRangeChange={handleVisibleRangeChange}
                        externalHoverTime={sharedHoverTime}
                        hideNativeCrosshair={true}
                        sharedTimeRange={sharedTimeRange}
                        isMobileMode={true}
                        hideTimeScale={index !== activeIndicators.length - 1}
                      />
                    </Box>
                  </Box>
                ))}
              </Box>
            )}
          </Box>
        ) : (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', flex: 1 }}>
            <Typography>데이터를 불러오는 중...</Typography>
          </Box>
        )}
      </Box>

      {/* ======================================================================== */}
      {/* 하단 툴바 (종목 선택, 시간 간격) - 간소화 */}
      {/* ======================================================================== */}
      {!isFullscreen && (
        <Paper
          elevation={3}
          sx={{
            height: `${layoutMetrics.TOOLBAR_HEIGHT}px`,
            display: 'flex',
            alignItems: 'center',
            px: 0.5,
            gap: 0.5,
            borderTop: 1,
            borderColor: 'divider',
          }}
        >
          {/* 종목명 (텍스트만) */}
          <Typography variant="body2" sx={{ pl: 1, fontWeight: 'bold', fontSize: '0.85rem' }}>
            {symbol.replace('KRW-', '')}
          </Typography>

          {/* 시간 간격 선택 (컴팩트) */}
          <FormControl size="small" sx={{ minWidth: 70 }}>
            <Select
              value={timeInterval}
              onChange={(e) => {
                const newInterval = e.target.value;
                setTimeInterval(newInterval);
                fetchChartData(symbol, newInterval);
              }}
              sx={{ fontSize: '0.75rem', height: 32 }}
            >
              <MenuItem value="1">1분</MenuItem>
              <MenuItem value="5">5분</MenuItem>
              <MenuItem value="15">15분</MenuItem>
              <MenuItem value="30">30분</MenuItem>
              <MenuItem value="60">1시간</MenuItem>
              <MenuItem value="240">4시간</MenuItem>
              <MenuItem value="days">일봉</MenuItem>
            </Select>
          </FormControl>

          <Box sx={{ flex: 1 }} />

          {/* 지표 설정 버튼 */}
          <IconButton size="small" onClick={() => setShowSettings(true)} sx={{ p: 0.5 }}>
            <TuneIcon fontSize="small" />
          </IconButton>
        </Paper>
      )}

      {/* ======================================================================== */}
      {/* Settings Drawer (보조지표 on/off) */}
      {/* ======================================================================== */}
      <Drawer anchor="left" open={showSettings} onClose={() => setShowSettings(false)}>
        <Box sx={{ width: 300, p: 2 }}>
          <Typography variant="h6" gutterBottom>
            보조지표 설정
          </Typography>
          <Divider sx={{ mb: 2 }} />

          <List>
            {[
              { key: 'volume', label: '거래량' },
              { key: 'macdLine', label: 'MACD' },
              { key: 'rsi', label: 'RSI' },
              { key: 'stochasticSlow', label: 'Stochastic' },
              { key: 'cci', label: 'CCI' },
              { key: 'adx', label: 'ADX' },
              { key: 'obv', label: 'OBV' },
              { key: 'newPsychological', label: '심리선' },
            ].map((item) => {
              const settingKey = item.key as keyof typeof indicatorVisibilitySettings;
              const value = indicatorVisibilitySettings[settingKey];
              const isChecked = typeof value === 'boolean' ? value : false;

              return (
                <ListItem key={item.key}>
                  <ListItemText primary={item.label} />
                  <ListItemSecondaryAction>
                    <Switch edge="end" checked={isChecked} onChange={() => handleIndicatorToggle(settingKey)} />
                  </ListItemSecondaryAction>
                </ListItem>
              );
            })}
          </List>

          <Divider sx={{ my: 2 }} />

          <Button fullWidth variant="outlined" onClick={() => setMaSettingsOpen(true)} sx={{ mb: 1 }}>
            이동평균선 설정
          </Button>
          <Button fullWidth variant="outlined" onClick={() => setIchimokuSettingsOpen(true)} sx={{ mb: 1 }}>
            일목균형표 설정
          </Button>
          <Button fullWidth variant="outlined" onClick={() => setBollingerSettingsOpen(true)} sx={{ mb: 1 }}>
            볼린저밴드 설정
          </Button>
          <Button fullWidth variant="outlined" onClick={() => setIndicatorParamsOpen(true)}>
            지표 파라미터 설정
          </Button>
        </Box>
      </Drawer>

      {/* ======================================================================== */}
      {/* Settings Dialogs */}
      {/* ======================================================================== */}
      <MASettingsDialog open={maSettingsOpen} onClose={() => setMaSettingsOpen(false)} />
      <IchimokuSettingsDialog open={ichimokuSettingsOpen} onClose={() => setIchimokuSettingsOpen(false)} />
      <BollingerSettingsDialog open={bollingerSettingsOpen} onClose={() => setBollingerSettingsOpen(false)} />
      <IndicatorParamsSettingsDialog open={indicatorParamsOpen} onClose={() => setIndicatorParamsOpen(false)} />
    </Box>
  );
};

export default MobileChartPage;
