import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import {
  Box,
  Paper,
  Typography,
  IconButton,
  Divider,
  Chip,
  CircularProgress,
  Alert,
  Slider,
  useTheme,
} from '@mui/material';
import {
  Close as CloseIcon,
  TrendingUp,
  TrendingDown,
  RemoveCircleOutline,
  Refresh,
  AutoAwesome,
  Opacity as OpacityIcon,
} from '@mui/icons-material';

export interface RealTimeAnalysisPanelRef {
  updateLastAnalysis: (content: string, recommendation: 'strong_buy' | 'buy' | 'hold' | 'sell' | 'strong_sell' | null) => void;
  appendToLastAnalysis: (chunk: string) => void;
  startNewAnalysis: () => void;
}

interface RealTimeAnalysisPanelProps {
  open: boolean;
  onClose: () => void;
  symbol: string;
  currentPrice: number | null;
  onAnalyze: () => Promise<void>;
  autoAnalyze: boolean;
  nextUpdateTime?: Date | null;
  timeInterval?: string;
}

interface AnalysisResult {
  timestamp: string;
  symbol: string;
  price: number;
  recommendation: 'strong_buy' | 'buy' | 'hold' | 'sell' | 'strong_sell' | null;
  content: string;
  loading: boolean;
}

const RealTimeAnalysisPanel = forwardRef<RealTimeAnalysisPanelRef, RealTimeAnalysisPanelProps>(({
  open,
  onClose,
  symbol,
  currentPrice,
  onAnalyze,
  autoAnalyze,
  nextUpdateTime,
  timeInterval,
}, ref) => {
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';
  const [analyses, setAnalyses] = useState<AnalysisResult[]>([]);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [opacity, setOpacity] = useState(5); // 투명도 (0=불투명, 100=완전투명)
  const [panelWidth, setPanelWidth] = useState(500); // 패널 너비
  const [isResizing, setIsResizing] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());
  const panelRef = useRef<HTMLDivElement>(null);
  const scrollBottomRef = useRef<HTMLDivElement>(null);
  const resizeStartXRef = useRef<number>(0);
  const resizeStartWidthRef = useRef<number>(0);

  // 현재 시간 1초마다 업데이트 (다음 갱신 시간 카운트다운용)
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  // 다음 갱신까지 남은 시간 계산 (useMemo로 최적화)
  const timeRemaining = React.useMemo(() => {
    if (!nextUpdateTime) return null;
    const diff = Math.max(0, Math.floor((nextUpdateTime.getTime() - currentTime.getTime()) / 1000));
    const minutes = Math.floor(diff / 60);
    const seconds = diff % 60;
    return {
      label: minutes > 0 ? `${minutes}분 ${seconds}초` : `${seconds}초`,
      color: (diff < 30 ? 'warning' : 'info') as 'warning' | 'info',
      seconds: diff,
    };
  }, [nextUpdateTime, currentTime]);

  // 부모 컴포넌트에서 호출할 수 있는 메서드 노출
  useImperativeHandle(ref, () => ({
    startNewAnalysis: () => {
      setIsAnalyzing(true);
      const newAnalysis: AnalysisResult = {
        timestamp: new Date().toLocaleTimeString('ko-KR'),
        symbol,
        price: currentPrice || 0,
        recommendation: null,
        content: '',
        loading: true,
      };
      // 누적 목록 형태로 추가하되, 10개 초과시 오래된 항목 제거
      setAnalyses(prev => {
        const updated = [...prev, newAnalysis];
        // 10개 초과하면 오래된 것부터 제거
        if (updated.length > 10) {
          return updated.slice(updated.length - 10);
        }
        return updated;
      });
    },
    updateLastAnalysis: (content: string, recommendation: 'strong_buy' | 'buy' | 'hold' | 'sell' | 'strong_sell' | null) => {
      setIsAnalyzing(false);
      
      // 면책 문구 자동 추가
      const disclaimerText = '\n\n⚠️ AI 분석은 투자 참고용이며, 최종 결정은 본인 책임입니다.';
      const finalContent = content + disclaimerText;
      
      setAnalyses(prev => {
        if (prev.length === 0) return prev;
        const updated = [...prev];
        updated[updated.length - 1] = {
          ...updated[updated.length - 1],
          loading: false,
          content: finalContent,
          recommendation,
        };
        return updated;
      });
    },
    appendToLastAnalysis: (chunk: string) => {
      setAnalyses(prev => {
        if (prev.length === 0) return prev;
        const updated = [...prev];
        updated[updated.length - 1] = {
          ...updated[updated.length - 1],
          content: updated[updated.length - 1].content + chunk,
        };
        return updated;
      });
    },
  }));

  // 자동 스크롤
  useEffect(() => {
    if (scrollBottomRef.current) {
      scrollBottomRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [analyses]);

  // 분석 실행
  const executeAnalysis = async () => {
    if (isAnalyzing) return;
    await onAnalyze();
  };

  // 리사이징 핸들러
  const handleResizeStart = (e: React.MouseEvent) => {
    e.preventDefault();
    setIsResizing(true);
    resizeStartXRef.current = e.clientX;
    resizeStartWidthRef.current = panelWidth;
  };

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (!isResizing) return;
      
      const deltaX = resizeStartXRef.current - e.clientX;
      const newWidth = Math.max(350, Math.min(800, resizeStartWidthRef.current + deltaX));
      setPanelWidth(newWidth);
    };

    const handleMouseUp = () => {
      setIsResizing(false);
    };

    if (isResizing) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isResizing, panelWidth]);

  // 패널 외부 클릭 시 닫기
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (panelRef.current && !panelRef.current.contains(event.target as Node)) {
        // 패널 외부 클릭 시 닫지 않음 (사용자가 명시적으로 닫기 버튼을 눌러야 함)
      }
    };

    if (open) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [open]);

  // 추천 칩 렌더링
  const renderRecommendationChip = (recommendation: string | null) => {
    if (!recommendation) return null;

    const config = {
      strong_buy: { label: '🚀 강력 매수', color: '#10b981' as const, bg: 'rgba(16, 185, 129, 0.1)' },
      buy: { label: '📈 매수', color: '#22c55e' as const, bg: 'rgba(34, 197, 94, 0.1)' },
      hold: { label: '⏸️ 관망', color: '#6366f1' as const, bg: 'rgba(99, 102, 241, 0.1)' },
      sell: { label: '📉 매도', color: '#ef4444' as const, bg: 'rgba(239, 68, 68, 0.1)' },
      strong_sell: { label: '🔻 강력 매도', color: '#dc2626' as const, bg: 'rgba(220, 38, 38, 0.1)' },
    };

    const cfg = config[recommendation as keyof typeof config];
    if (!cfg) return null;

    return (
      <Chip
        label={cfg.label}
        size="small"
        sx={{
          fontWeight: 600,
          color: cfg.color,
          backgroundColor: cfg.bg,
          border: `1px solid ${cfg.color}`,
        }}
      />
    );
  };

  if (!open) return null;

  return (
    <>
      {/* 리사이즈 핸들 */}
      <Box
        onMouseDown={handleResizeStart}
        sx={{
          position: 'fixed',
          right: panelWidth,
          top: 0,
          bottom: 0,
          width: 4,
          zIndex: 1301,
          cursor: 'ew-resize',
          bgcolor: isResizing ? 'primary.main' : 'transparent',
          '&:hover': {
            bgcolor: 'primary.light',
          },
          transition: 'background-color 0.2s',
        }}
      />
      
      <Paper
        ref={panelRef}
        elevation={8}
        sx={{
          position: 'fixed',
          right: 0,
          top: 0,
          bottom: 0,
          width: { xs: '100%', sm: panelWidth },
          maxWidth: panelWidth,
          zIndex: 1300,
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          borderRadius: 0,
          borderLeft: '1px solid',
          borderColor: 'divider',
          bgcolor: isDark 
            ? `rgba(18, 18, 18, ${(100 - opacity) / 100})` 
            : `rgba(255, 255, 255, ${(100 - opacity) / 100})`,
          backdropFilter: opacity > 5 ? 'blur(10px)' : 'none',
        }}
      >
        {/* 헤더 */}
        <Box
          sx={{
            p: 2,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            bgcolor: isDark
              ? `rgba(25, 118, 210, ${(100 - opacity) / 100})`
              : `rgba(25, 118, 210, ${(100 - opacity) / 100})`,
            color: 'primary.contrastText',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <AutoAwesome />
            <Typography variant="h6" sx={{ fontWeight: 600 }}>
              실시간 AI 분석
            </Typography>
            {autoAnalyze && (
              <Chip
                label="자동"
                size="small"
                sx={{
                  bgcolor: 'rgba(255,255,255,0.2)',
                  color: 'white',
                  fontSize: '0.7rem',
                  height: 20,
                }}
              />
            )}
          </Box>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <IconButton
              size="small"
              onClick={executeAnalysis}
              disabled={isAnalyzing}
              sx={{ color: 'white' }}
            >
              {isAnalyzing ? <CircularProgress size={20} color="inherit" /> : <Refresh />}
            </IconButton>
            <IconButton size="small" onClick={onClose} sx={{ color: 'white' }}>
              <CloseIcon />
            </IconButton>
          </Box>
        </Box>

        {/* 투명도 조절 */}
        <Box sx={{ 
          p: 2, 
          bgcolor: isDark
            ? `rgba(30, 30, 30, ${(100 - opacity) / 100})`
            : `rgba(245, 245, 245, ${(100 - opacity) / 100})`,
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <OpacityIcon sx={{ color: 'text.secondary', fontSize: 20 }} />
            <Typography variant="caption" color="text.secondary" sx={{ minWidth: 60 }}>
              투명도 {opacity}%
            </Typography>
            <Slider
              value={opacity}
              onChange={(_, value) => setOpacity(value as number)}
              min={0}
              max={100}
              step={5}
              size="small"
              sx={{
                flex: 1,
                '& .MuiSlider-thumb': {
                  width: 16,
                  height: 16,
                },
              }}
            />
          </Box>
        </Box>

        <Divider />

      {/* 현재 종목 정보 */}
      <Box sx={{ 
        p: 1.5,
        bgcolor: isDark
          ? `rgba(30, 30, 30, ${Math.min(1, (100 - opacity) / 100 + 0.3)})`
          : `rgba(240, 240, 240, ${Math.min(1, (100 - opacity) / 100 + 0.3)})`,
      }}>
        {/* 1줄: 분석 종목 | 현재가 */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 0.5 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Typography variant="caption" color="text.secondary">
              분석 종목
            </Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>
              {symbol}
            </Typography>
          </Box>
          {currentPrice && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography variant="caption" color="text.secondary">
                현재가
              </Typography>
              <Typography variant="body2" sx={{ fontWeight: 600, color: 'success.main' }}>
                {currentPrice.toLocaleString()}원
              </Typography>
            </Box>
          )}
        </Box>
        
        {/* 2줄: 다음 갱신 | 갱신 간격 */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          {autoAnalyze && nextUpdateTime && timeRemaining ? (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography variant="caption" color="text.secondary">
                다음 갱신
              </Typography>
              <Chip 
                label={timeRemaining.label}
                size="small"
                color={timeRemaining.color}
                sx={{ 
                  fontWeight: 600,
                  fontSize: '0.65rem',
                  height: 20,
                }} 
              />
            </Box>
          ) : (
            <Box />
          )}
          {timeInterval && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Typography variant="caption" color="text.secondary">
                갱신 간격
              </Typography>
              <Typography variant="caption" sx={{ fontWeight: 600 }}>
                {timeInterval}분봉
              </Typography>
            </Box>
          )}
        </Box>
      </Box>

      <Divider />

      {/* 분석 결과 목록 */}
      <Box
        sx={{
          flex: 1,
          overflowY: 'auto',
          p: 2,
          '&::-webkit-scrollbar': {
            width: '8px',
          },
          '&::-webkit-scrollbar-track': {
            background: 'transparent',
          },
          '&::-webkit-scrollbar-thumb': {
            background: isDark ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.2)',
            borderRadius: '4px',
          },
          '&::-webkit-scrollbar-thumb:hover': {
            background: isDark ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.3)',
          },
        }}
      >
        {analyses.length === 0 ? (
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100%',
              gap: 2,
            }}
          >
            <AutoAwesome sx={{ fontSize: 60, color: 'text.disabled' }} />
            <Typography variant="body2" color="text.secondary" align="center">
              {autoAnalyze
                ? '1분마다 자동으로 AI 분석이 실행됩니다.'
                : '새로고침 버튼을 눌러 AI 분석을 시작하세요.'}
            </Typography>
          </Box>
        ) : (
          analyses.map((analysis, index) => (
            <Box key={index} sx={{ mb: index < analyses.length - 1 ? 3 : 0 }}>
              {/* 분석 헤더 */}
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                <Typography variant="caption" color="text.secondary">
                  {analysis.timestamp} | {analysis.symbol}
                </Typography>
                {renderRecommendationChip(analysis.recommendation)}
              </Box>

              {/* 분석 내용 */}
              <Paper
                elevation={1}
                sx={{
                  p: 2,
                  bgcolor: isDark
                    ? `rgba(40, 40, 40, ${Math.min(1, (100 - opacity) / 100 + 0.2)})`
                    : `rgba(250, 250, 250, ${Math.min(1, (100 - opacity) / 100 + 0.2)})`,
                  borderRadius: 2,
                  border: '1px solid',
                  borderColor: 'divider',
                }}
              >
                {analysis.loading ? (
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <CircularProgress size={16} />
                    <Typography variant="body2" color="text.secondary">
                      AI 분석 중...
                    </Typography>
                  </Box>
                ) : (
                  <Typography
                    variant="body2"
                    sx={{
                      whiteSpace: 'pre-wrap',
                      wordBreak: 'break-word',
                      lineHeight: 1.6,
                    }}
                  >
                    {analysis.content || '분석 대기 중...'}
                  </Typography>
                )}
              </Paper>

              {index < analyses.length - 1 && <Divider sx={{ my: 2 }} />}
            </Box>
          ))
        )}
        <div ref={scrollBottomRef} />
      </Box>

      </Paper>
    </>
  );
});

RealTimeAnalysisPanel.displayName = 'RealTimeAnalysisPanel';

export default RealTimeAnalysisPanel;
