import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
  Box,
  IconButton,
  Typography,
  Slider,
  useTheme,
  Tab,
  Tabs,
} from '@mui/material';
import {
  Close as CloseIcon,
  DragHandle,
  Opacity as OpacityIcon,
} from '@mui/icons-material';
import {
  ComposedChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  ReferenceLine,
  ResponsiveContainer,
  Bar,
  Customized,
} from 'recharts';
import { useChartColors } from '../contexts/ChartColorContext';
import { useIndicatorSettings } from '../contexts/IndicatorSettingsContext';
import { useIndicatorPopup } from '../contexts/IndicatorPopupContext';

interface IndicatorPopupWindowProps {
  open: boolean;
  onClose: () => void;
  chartData: any[];
  chartMargin?: { top: number; right: number; bottom: number; left: number };
}

const IndicatorPopupWindow: React.FC<IndicatorPopupWindowProps> = ({
  open,
  onClose,
  chartData,
  chartMargin = { top: 5, right: 55, bottom: 20, left: 55 },
}) => {
  const { colors } = useChartColors();
  const { indicatorSettings } = useIndicatorSettings();
  const { hoveredIndex, activeIndicatorType } = useIndicatorPopup();
  const theme = useTheme();
  
  // 팝업 상태
  const [popupTransparency, setPopupTransparency] = useState(30); // 기본값: 30% (약간 투명)
  const [height, setHeight] = useState(40); // 화면 높이의 40%
  const [isResizing, setIsResizing] = useState(false);
  const resizeRef = useRef<HTMLDivElement>(null);
  
  // 확대 표시 범위 (마우스 위치 기준 전후 개수)
  const ZOOM_RANGE = 10; // 전후 10개씩 총 21개 데이터 표시
  
  // 마우스 위치 기준으로 확대할 데이터 추출
  const zoomedData = useMemo(() => {
    if (!hoveredIndex || chartData.length === 0) {
      const endIndex = chartData.length - 1;
      const startIndex = Math.max(0, endIndex - ZOOM_RANGE * 2);
      return chartData.slice(startIndex, endIndex + 1);
    }
    
    const startIndex = Math.max(0, hoveredIndex - ZOOM_RANGE);
    const endIndex = Math.min(chartData.length - 1, hoveredIndex + ZOOM_RANGE);
    return chartData.slice(startIndex, endIndex + 1);
  }, [chartData, hoveredIndex]);
  
  // 드래그로 높이 조절
  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setIsResizing(true);
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    if (e.touches.length === 1) {
      setIsResizing(true);
    }
  };
  
  useEffect(() => {
    const handleMove = (e: MouseEvent | TouchEvent) => {
      if (!isResizing) return;
      
      let clientY: number;
      if ('touches' in e) {
        if (e.touches.length === 0) return;
        clientY = e.touches[0].clientY;
        e.preventDefault();
      } else {
        clientY = e.clientY;
      }
      
      const windowHeight = window.innerHeight;
      const newHeight = Math.max(20, Math.min(80, ((windowHeight - clientY) / windowHeight) * 100));
      setHeight(newHeight);
    };
    
    const handleEnd = () => {
      setIsResizing(false);
    };
    
    if (isResizing) {
      document.addEventListener('mousemove', handleMove);
      document.addEventListener('mouseup', handleEnd);
      document.addEventListener('touchmove', handleMove, { passive: false });
      document.addEventListener('touchend', handleEnd);
    }
    
    return () => {
      document.removeEventListener('mousemove', handleMove);
      document.removeEventListener('mouseup', handleEnd);
      document.removeEventListener('touchmove', handleMove);
      document.removeEventListener('touchend', handleEnd);
    };
  }, [isResizing]);
  
  // X축 레이블 포맷
  const formatXAxisLabel = (dateStr: string) => {
    return dateStr || '';
  };
  
  // Y축 숫자 포맷
  const formatYAxis = (value: number): string => {
    if (value === null || value === undefined) return '';
    const absValue = Math.abs(value);
    if (absValue >= 1000) return (value / 1000).toFixed(1) + 'K';
    if (absValue >= 100) return Math.round(value).toString();
    if (absValue >= 1) return value.toFixed(1);
    return value.toFixed(2);
  };
  
  // 마우스 위치 크로스헤어
  const VerticalCrosshair = (props: any) => {
    const { xAxisMap, offset } = props;
    
    if (!hoveredIndex || !xAxisMap || !zoomedData) return null;
    
    const startIndex = Math.max(0, hoveredIndex - ZOOM_RANGE);
    const indexInZoomedData = hoveredIndex - startIndex;
    
    if (indexInZoomedData < 0 || indexInZoomedData >= zoomedData.length) return null;
    
    const data = zoomedData[indexInZoomedData];
    if (!data) return null;
    
    const xAxis = xAxisMap[0];
    if (!xAxis) return null;
    
    const x = xAxis.scale(data.date);
    if (x === undefined || isNaN(x)) return null;
    
    const y1 = offset?.top || 0;
    const y2 = (offset?.top || 0) + (offset?.height || 0);
    
    return (
      <line
        x={x}
        y={y1}
        x1={x}
        y1={y1}
        x2={x}
        y2={y2}
        stroke="#4caf50"
        strokeWidth={2}
        opacity={0.8}
        pointerEvents="none"
      />
    );
  };
  
  if (!open || !activeIndicatorType) return null;
  
  // 차트 타이틀과 정보
  const getIndicatorTitle = () => {
    switch (activeIndicatorType) {
      case 'macd':
        return `MACD (${indicatorSettings.macdFastPeriod},${indicatorSettings.macdSlowPeriod},${indicatorSettings.macdSignalPeriod})`;
      case 'stochastic':
        return `STOCHASTIC (${indicatorSettings.stochasticKPeriod},${indicatorSettings.stochasticDPeriod},${indicatorSettings.stochasticSlowing})`;
      case 'rsi':
        return `RSI (${indicatorSettings.rsiPeriod})`;
      case 'volume':
        return 'VOLUME';
      default:
        return '';
    }
  };
  
  // 차트 높이 계산
  const chartHeight = (height * window.innerHeight / 100) - 60;
  
  return (
    <Box
      sx={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        height: `${height}vh`,
        bgcolor: `rgba(${theme.palette.mode === 'dark' ? '18, 18, 26' : '255, 255, 255'}, ${1 - popupTransparency / 100})`,
        backdropFilter: popupTransparency < 50 ? 'blur(10px)' : 'none',
        zIndex: 1300,
        display: 'flex',
        flexDirection: 'column',
        borderTop: '2px solid',
        borderColor: 'primary.main',
        transition: isResizing ? 'none' : 'height 0.1s ease',
      }}
    >
      {/* 드래그 핸들 */}
      <Box
        ref={resizeRef}
        onMouseDown={handleMouseDown}
        onTouchStart={handleTouchStart}
        sx={{
          height: 12,
          bgcolor: 'primary.dark',
          cursor: 'ns-resize',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          touchAction: 'none',
          '&:hover': {
            bgcolor: 'primary.main',
          },
        }}
      >
        <DragHandle sx={{ fontSize: 16, color: 'text.secondary' }} />
      </Box>
      
      {/* 헤더 */}
      <Box
        sx={{
          px: 2,
          py: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          borderBottom: '1px solid',
          borderColor: 'divider',
          bgcolor: `rgba(${theme.palette.mode === 'dark' ? '30, 30, 46' : '245, 245, 245'}, ${Math.max(1 - popupTransparency / 100, 0.3)})`,
        }}
      >
        <Typography variant="subtitle1" fontWeight="bold" sx={{ color: 'primary.light' }}>
          📊 {getIndicatorTitle()}
        </Typography>
        
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          {/* 투명도 조절 */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: 200 }}>
            <OpacityIcon sx={{ fontSize: 18, color: 'text.secondary' }} />
            <Typography variant="caption" sx={{ color: 'text.secondary', minWidth: 45 }}>
              투명도
            </Typography>
            <Slider
              value={popupTransparency}
              onChange={(_, value) => setPopupTransparency(value as number)}
              min={0}
              max={100}
              step={5}
              size="small"
              sx={{ width: 120 }}
            />
            <Typography variant="caption" sx={{ color: 'text.secondary', minWidth: 40 }}>
              {popupTransparency}%
            </Typography>
          </Box>
          
          {/* 닫기 버튼 */}
          <IconButton 
            size="small" 
            onClick={onClose} 
            sx={{ 
              bgcolor: 'action.hover',
              '&:hover': { bgcolor: 'error.main', color: 'error.contrastText' },
            }}
          >
            <CloseIcon fontSize="small" />
          </IconButton>
        </Box>
      </Box>
      
      {/* 차트 영역 */}
      <Box sx={{ flex: 1, p: 2 }}>
        {activeIndicatorType === 'macd' && (
          <ResponsiveContainer width="100%" height={chartHeight}>
            <ComposedChart data={zoomedData} margin={chartMargin}>
              <CartesianGrid stroke="#2d3748" strokeWidth={0.5} strokeDasharray="3 3" />
              <XAxis
                dataKey="date"
                type="category"
                tick={{ fontSize: 11, fill: '#8b95a5' }}
                tickLine={{ stroke: '#3a4557' }}
                axisLine={{ stroke: '#3a4557' }}
                tickFormatter={formatXAxisLabel}
                interval="preserveStartEnd"
              />
              <YAxis
                tick={{ fontSize: 12, fill: '#8b95a5' }}
                tickLine={{ stroke: '#3a4557' }}
                axisLine={{ stroke: '#3a4557' }}
                tickFormatter={formatYAxis}
                width={60}
              />
              
              <Customized component={VerticalCrosshair} />
              
              <ReferenceLine y={0} stroke="#666" strokeDasharray="3 3" strokeWidth={1} />
              
              {/* 히스토그램 */}
              <Bar dataKey="macdHistogram" radius={[2, 2, 0, 0]}>
                {zoomedData.map((entry, index) => (
                  <rect
                    key={`hist-${index}`}
                    fill={entry.macdHistogram >= 0 ? colors.histogramPositive : colors.histogramNegative}
                    opacity={0.8}
                  />
                ))}
              </Bar>
              
              {/* MACD 라인 */}
              <Line
                type="monotone"
                dataKey="macdLine"
                stroke={colors.macdLine}
                strokeWidth={2.5}
                dot={{ r: 4, fill: colors.macdLine }}
                isAnimationActive={false}
              />
              
              {/* Signal 라인 */}
              <Line
                type="monotone"
                dataKey="signalLine"
                stroke={colors.signalLine}
                strokeWidth={2.5}
                dot={{ r: 4, fill: colors.signalLine }}
                isAnimationActive={false}
              />
            </ComposedChart>
          </ResponsiveContainer>
        )}
          
        {activeIndicatorType === 'stochastic' && (
          <ResponsiveContainer width="100%" height={chartHeight}>
            <ComposedChart data={zoomedData} margin={chartMargin}>
              <CartesianGrid stroke="#2d3748" strokeWidth={0.5} strokeDasharray="3 3" />
              <XAxis
                dataKey="date"
                type="category"
                tick={{ fontSize: 11, fill: '#8b95a5' }}
                tickLine={{ stroke: '#3a4557' }}
                axisLine={{ stroke: '#3a4557' }}
                tickFormatter={formatXAxisLabel}
                interval="preserveStartEnd"
              />
              <YAxis
                domain={[0, 100]}
                tick={{ fontSize: 12, fill: '#8b95a5' }}
                tickLine={{ stroke: '#3a4557' }}
                axisLine={{ stroke: '#3a4557' }}
                tickFormatter={formatYAxis}
                width={60}
              />
              
              <Customized component={VerticalCrosshair} />
              
              <ReferenceLine y={indicatorSettings.stochasticOverbought} stroke={colors.stochasticOverboughtColor} strokeDasharray="3 3" strokeWidth={1} />
              <ReferenceLine y={indicatorSettings.stochasticNeutral} stroke={colors.stochasticNeutralColor} strokeDasharray="3 3" strokeWidth={1} />
              <ReferenceLine y={indicatorSettings.stochasticOversold} stroke={colors.stochasticOversoldColor} strokeDasharray="3 3" strokeWidth={1} />
              
              <Line
                type="monotone"
                dataKey="stochasticK"
                stroke={colors.stochasticK}
                strokeWidth={2.5}
                dot={{ r: 4, fill: colors.stochasticK }}
                isAnimationActive={false}
              />
              
              <Line
                type="monotone"
                dataKey="stochasticD"
                stroke={colors.stochasticD}
                strokeWidth={2.5}
                dot={{ r: 4, fill: colors.stochasticD }}
                isAnimationActive={false}
              />
            </ComposedChart>
          </ResponsiveContainer>
        )}
      </Box>
    </Box>
  );
};

export default IndicatorPopupWindow;
