import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Select,
  MenuItem,
  FormControl,
  CircularProgress,
  Alert,
  Chip,
  Paper,
  Tabs,
  Tab,
} from '@mui/material';
import {
  ArrowBack,
  StarBorder,
  NotificationsNone,
  Share,
  ChevronLeft,
  ChevronRight,
  Settings,
  Fullscreen,
} 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 { useIndicatorVisibility } from '../contexts/IndicatorVisibilityContext';
import { useIndicatorSettings } from '../contexts/IndicatorSettingsContext';
import { useChartColors } from '../contexts/ChartColorContext';

/**
 * 업비트 스타일 모바일 차트 페이지
 */
const MobileChartPageUpbit: React.FC = () => {
  // ============================================================================
  // Contexts
  // ============================================================================
  const { symbol, setSymbol, timeInterval, setTimeInterval, macdData, loading, error, fetchChartData } = useUpbitData();
  const { settings: indicatorVisibilitySettings } = useIndicatorVisibility();
  const { indicatorSettings: paramSettings } = useIndicatorSettings();
  const { colors: colorSettings } = useChartColors();
  const { themeMode } = useAppTheme();

  // ============================================================================
  // Refs
  // ============================================================================
  const chartRef = useRef<ChartHandle>(null);

  // ============================================================================
  // States
  // ============================================================================
  const [selectedTab, setSelectedTab] = useState(2); // 0:주문, 1:호가, 2:차트, 3:시세, 4:정보
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [candleChartHeightRatio, setCandleChartHeightRatio] = useState(0.5);
  const [isResizing, setIsResizing] = useState(false);

  // Chart sync 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);

  // ============================================================================
  // Data transformation
  // ============================================================================
  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]);

  // 가격 정보
  const priceInfo = useMemo(() => {
    if (!macdData || macdData.length === 0) return null;
    const latest = macdData[macdData.length - 1];
    const previous = macdData.length > 1 ? macdData[macdData.length - 2] : latest;
    const changeAmount = latest.close - previous.close;
    const changePercent = (changeAmount / previous.close) * 100;
    return {
      price: latest.close,
      changeAmount,
      changePercent,
      isPositive: changeAmount >= 0,
    };
  }, [macdData]);

  // Active indicators
  const activeIndicators = useMemo(() => {
    const indicators: Array<{ key: string; type: string; label: string }> = [];
    if (indicatorVisibilitySettings.volume) indicators.push({ key: 'volume', type: 'volume', label: '거래량' });
    if (indicatorVisibilitySettings.macdLine || indicatorVisibilitySettings.macdHistogram) {
      indicators.push({ key: 'macd', type: 'macd', label: 'MACD' });
    }
    if (indicatorVisibilitySettings.stochasticSlow) {
      indicators.push({ key: 'stochastic', type: 'stochastic', label: 'Stochastic Slow' });
    }
    return indicators;
  }, [indicatorVisibilitySettings]);

  // Layout calculation
  const layoutMetrics = useMemo(() => {
    const PRICE_INFO_HEIGHT = 80;
    const TABS_HEIGHT = 48;
    const CHART_CONTROL_HEIGHT = 40;
    const RESIZER_HEIGHT = 4;
    const INDICATOR_TITLE_HEIGHT = 20;

    const availableHeight = Math.max(500, window.innerHeight - PRICE_INFO_HEIGHT - TABS_HEIGHT - CHART_CONTROL_HEIGHT);
    const candleHeight = Math.max(250, Math.floor(availableHeight * candleChartHeightRatio));
    const indicatorAreaHeight = Math.max(0, availableHeight - candleHeight - (activeIndicators.length > 0 ? RESIZER_HEIGHT : 0));
    const singleIndicatorHeight = activeIndicators.length > 0 ? Math.max(60, Math.floor(indicatorAreaHeight / activeIndicators.length)) : 0;
    const chartHeight = Math.max(40, singleIndicatorHeight - INDICATOR_TITLE_HEIGHT);

    return {
      PRICE_INFO_HEIGHT,
      TABS_HEIGHT,
      CHART_CONTROL_HEIGHT,
      RESIZER_HEIGHT,
      INDICATOR_TITLE_HEIGHT,
      availableHeight,
      candleHeight,
      indicatorAreaHeight,
      singleIndicatorHeight,
      chartHeight,
    };
  }, [candleChartHeightRatio, activeIndicators.length]);

  // ============================================================================
  // Handlers
  // ============================================================================
  const handleVisibleRangeChange = useCallback((from: number, to: number) => {
    if (syncThrottleTimer.current) clearTimeout(syncThrottleTimer.current);
    syncThrottleTimer.current = setTimeout(() => setSharedTimeRange({ from, to }), 100);
  }, []);

  const handleCrosshairMove = useCallback((time: Time | null) => {
    setSharedHoverTime(time);
  }, []);

  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;
      newRatio = Math.max(0.3, Math.min(0.7, 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);
  };

  // ============================================================================
  // Render
  // ============================================================================
  return (
    <Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column', overflow: 'hidden', bgcolor: 'background.default' }}>
      {/* ====================================================================== */}
      {/* 상단 헤더 */}
      {/* ====================================================================== */}
      <AppBar position="static" elevation={0} sx={{ bgcolor: 'background.paper' }}>
        <Toolbar sx={{ minHeight: '56px !important', px: 1 }}>
          <IconButton edge="start" size="small"><ArrowBack /></IconButton>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flex: 1, ml: 1 }}>
            <Typography variant="body2" fontWeight="bold" sx={{ fontSize: '0.9rem' }}>
              {symbol.replace('KRW-', '')}
            </Typography>
          </Box>
          <IconButton size="small"><StarBorder fontSize="small" /></IconButton>
          <IconButton size="small"><NotificationsNone fontSize="small" /></IconButton>
          <IconButton size="small"><Share fontSize="small" /></IconButton>
        </Toolbar>
      </AppBar>

      {/* ====================================================================== */}
      {/* 가격 정보 영역 */}
      {/* ====================================================================== */}
      <Box sx={{ height: `${layoutMetrics.PRICE_INFO_HEIGHT}px`, bgcolor: 'background.paper', px: 2, py: 1, borderBottom: 1, borderColor: 'divider' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Box>
            <Typography variant="h5" fontWeight="bold" sx={{ color: priceInfo?.isPositive ? 'error.main' : 'primary.main' }}>
              {priceInfo?.price.toLocaleString() || '0'}
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, mt: 0.5 }}>
              <Typography variant="body2" sx={{ color: priceInfo?.isPositive ? 'error.main' : 'primary.main' }}>
                {priceInfo?.isPositive ? '+' : ''}{priceInfo?.changePercent.toFixed(2)}%
              </Typography>
              <Typography variant="body2" sx={{ color: priceInfo?.isPositive ? 'error.main' : 'primary.main' }}>
                {priceInfo?.isPositive ? '+' : ''}{priceInfo?.changeAmount.toLocaleString()}
              </Typography>
            </Box>
          </Box>
          <Box sx={{ display: 'flex', gap: 0.5, alignItems: 'center' }}>
            <IconButton size="small"><ChevronLeft fontSize="small" /></IconButton>
            <Box sx={{ width: 60, height: 30, bgcolor: 'action.hover', borderRadius: 0.5 }} />
            <IconButton size="small"><ChevronRight fontSize="small" /></IconButton>
          </Box>
        </Box>
      </Box>

      {/* ====================================================================== */}
      {/* 탭 메뉴 */}
      {/* ====================================================================== */}
      <Box sx={{ bgcolor: 'background.paper', borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={selectedTab} onChange={(_, v) => setSelectedTab(v)} variant="fullWidth">
          <Tab label="주문" sx={{ minHeight: `${layoutMetrics.TABS_HEIGHT}px`, fontSize: '0.85rem' }} />
          <Tab label="호가" sx={{ minHeight: `${layoutMetrics.TABS_HEIGHT}px`, fontSize: '0.85rem' }} />
          <Tab label="차트" sx={{ minHeight: `${layoutMetrics.TABS_HEIGHT}px`, fontSize: '0.85rem' }} />
          <Tab label="시세" sx={{ minHeight: `${layoutMetrics.TABS_HEIGHT}px`, fontSize: '0.85rem' }} />
          <Tab label="정보" sx={{ minHeight: `${layoutMetrics.TABS_HEIGHT}px`, fontSize: '0.85rem' }} />
        </Tabs>
      </Box>

      {/* ====================================================================== */}
      {/* 차트 컨트롤 바 */}
      {/* ====================================================================== */}
      <Box sx={{ height: `${layoutMetrics.CHART_CONTROL_HEIGHT}px`, bgcolor: 'background.paper', display: 'flex', alignItems: 'center', px: 1, gap: 1, borderBottom: 1, borderColor: 'divider' }}>
        <FormControl size="small" sx={{ minWidth: 70 }}>
          <Select value={symbol} sx={{ fontSize: '0.75rem', height: 28 }}>
            <MenuItem value={symbol}>{symbol.replace('KRW-', '')}</MenuItem>
          </Select>
        </FormControl>
        
        <Chip label="초" size="small" sx={{ height: 24, fontSize: '0.7rem' }} />
        <Chip label="1분" size="small" sx={{ height: 24, fontSize: '0.7rem' }} />
        <Chip label="1시간" size="small" variant="filled" color="primary" sx={{ height: 24, fontSize: '0.7rem' }} />
        <Chip label="일" size="small" sx={{ height: 24, fontSize: '0.7rem' }} />
        <Chip label="주" size="small" sx={{ height: 24, fontSize: '0.7rem' }} />
        
        <Box sx={{ flex: 1 }} />
        <IconButton size="small" sx={{ p: 0.5 }}><Fullscreen fontSize="small" /></IconButton>
        <IconButton size="small" sx={{ p: 0.5 }}><Settings fontSize="small" /></IconButton>
      </Box>

      {/* ====================================================================== */}
      {/* 차트 영역 */}
      {/* ====================================================================== */}
      {loading && candleData.length === 0 ? (
        <Box sx={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <CircularProgress />
        </Box>
      ) : error ? (
        <Box sx={{ flex: 1, 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}
            />
          </Box>

          {/* 리사이저 */}
          {activeIndicators.length > 0 && (
            <Box
              onMouseDown={handleResizerMouseDown}
              onTouchStart={handleResizerMouseDown}
              sx={{
                height: `${layoutMetrics.RESIZER_HEIGHT}px`,
                bgcolor: isResizing ? 'primary.main' : 'divider',
                cursor: 'ns-resize',
                '&:active': { bgcolor: 'primary.main' },
              }}
            />
          )}

          {/* 보조지표 */}
          {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" sx={{ fontSize: '0.65rem', fontWeight: 'bold' }}>{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={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Typography>데이터를 불러오는 중...</Typography>
        </Box>
      )}
    </Box>
  );
};

export default MobileChartPageUpbit;
