import React, { useState, useEffect, useMemo } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Chip,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Slider,
  IconButton,
  Tooltip,
  CircularProgress,
  Alert,
  Tabs,
  Tab,
  InputAdornment,
  Paper,
  Grid,
} from '@mui/material';
import {
  Search as SearchIcon,
  CloudUpload as UploadIcon,
} from '@mui/icons-material';
import { useAppTheme } from '../contexts/ThemeContext';
import PatternCanvas from '../components/PatternCanvas';
import {
  searchPattern,
  getPatternTemplates,
  PatternTemplate,
  PatternMatchResult,
  PatternSearchRequest,
  getCategoryName,
  getDirectionName,
  getFrequencyName,
  DEFAULT_PATTERN_TEMPLATES,
  fetchCandleData,
  CandleDataForChart,
} from '../services/patternApi';
import CandlestickChart from '../components/CandlestickChart';
import { CandleData } from '../services/backtestApi';

const PatternSearchPage: React.FC = () => {
  const { themeMode } = useAppTheme();
  const isDark = themeMode === 'dark';
  
  // 상태 관리
  const [templates, setTemplates] = useState<PatternTemplate[]>([]);
  const [selectedPattern, setSelectedPattern] = useState<PatternTemplate | null>(null);
  const [patternSearch, setPatternSearch] = useState('');
  const [drawnPatternData, setDrawnPatternData] = useState<number[]>([]);
  
  // 검색 옵션
  const [market, setMarket] = useState('KRW');
  const [timeframe, setTimeframe] = useState('1d');
  const [minSimilarity, setMinSimilarity] = useState(75);
  const [mirrorSearch, setMirrorSearch] = useState(false);
  
  // 검색 결과
  const [results, setResults] = useState<PatternMatchResult[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // UI 상태
  const [activeTab, setActiveTab] = useState(0); // 0: 직접 그리기, 1: 패턴 선택, 2: 이미지 업로드
  const [centerTab, setCenterTab] = useState(0); // 0: 패턴입력, 1: 차트
  const [sortBy, setSortBy] = useState<'similarity' | 'expectedReturn' | 'successRate'>('similarity');
  const [libraryTab, setLibraryTab] = useState(0); // 0: 추세패턴, 1: 캔들패턴
  
  // 차트 상태
  const [selectedSymbol, setSelectedSymbol] = useState<PatternMatchResult | null>(null);
  const [chartData, setChartData] = useState<CandleData[]>([]);
  const [isLoadingChart, setIsLoadingChart] = useState(false);
  
  // 패턴 템플릿 로드
  useEffect(() => {
    const loadTemplates = async () => {
      try {
        const response = await getPatternTemplates();
        if (response.success && response.templates.length > 0) {
          setTemplates(response.templates);
        } else {
          // 백엔드 연결 실패 시 기본 패턴 사용
          console.log('백엔드 연결 실패, 기본 패턴 템플릿 사용');
          setTemplates(DEFAULT_PATTERN_TEMPLATES);
        }
      } catch (error) {
        console.log('패턴 템플릿 로드 실패, 기본 패턴 사용:', error);
        setTemplates(DEFAULT_PATTERN_TEMPLATES);
      }
    };
    loadTemplates();
  }, []);
  
  // 카테고리별 패턴 그룹화
  const groupedTemplates = useMemo(() => {
    const filtered = templates.filter(t => 
      t.name.toLowerCase().includes(patternSearch.toLowerCase()) ||
      t.nameEn.toLowerCase().includes(patternSearch.toLowerCase())
    );
    
    return {
      REVERSAL: filtered.filter(t => t.category === 'REVERSAL'),
      CONTINUATION: filtered.filter(t => t.category === 'CONTINUATION'),
      CANDLE: filtered.filter(t => t.category === 'CANDLE'),
    };
  }, [templates, patternSearch]);
  
  // 패턴 검색 실행
  const handleSearch = async () => {
    setIsSearching(true);
    setError(null);
    
    const request: PatternSearchRequest = {
      patternData: drawnPatternData.length > 0 ? drawnPatternData : undefined,
      patternType: selectedPattern?.type,
      market,
      timeframe,
      minSimilarity,
      maxResults: 50,
      mirrorSearch,
    };
    
    const response = await searchPattern(request);
    
    if (response.success) {
      setResults(response.results);
    } else {
      setError(response.error || '검색 중 오류가 발생했습니다.');
    }
    
    setIsSearching(false);
  };
  
  // 패턴 선택
  const handlePatternSelect = (pattern: PatternTemplate) => {
    setSelectedPattern(pattern);
    setDrawnPatternData(pattern.data);
  };
  
  // 캔버스에서 패턴 그리기
  const handlePatternDraw = (data: number[]) => {
    setDrawnPatternData(data);
    if (data.length > 0) {
      setSelectedPattern(null); // 직접 그린 경우 템플릿 선택 해제
    }
  };
  
  // 결과 정렬
  const sortedResults = useMemo(() => {
    return [...results].sort((a, b) => {
      switch (sortBy) {
        case 'expectedReturn':
          return b.expectedReturn - a.expectedReturn;
        case 'successRate':
          return b.successRate - a.successRate;
        default:
          return b.similarity - a.similarity;
      }
    });
  }, [results, sortBy]);
  
  // 초기화
  const handleReset = () => {
    setSelectedPattern(null);
    setDrawnPatternData([]);
    setResults([]);
    setError(null);
  };
  
  // 시간봉별 차트 표시 캔들 개수 (최대 범위 기준)
  const getCandleCountForChart = (tf: string): number => {
    switch (tf.toLowerCase()) {
      case '1m': return 300;   // 5시간 = 300분
      case '3m': return 300;   // 15시간 = 300개 * 3분
      case '5m': return 300;   // 25시간 = 300개 * 5분
      case '10m': return 200;  // 33시간 = 200개 * 10분
      case '15m': return 200;  // 50시간 = 200개 * 15분
      case '30m': return 200;  // 100시간 = 200개 * 30분
      case '1h': return 200;   // 200시간 ≈ 8일
      case '4h': return 200;   // 800시간 ≈ 33일
      case '1d': return 200;   // 200일 ≈ 6개월
      case '1w': return 200;   // 200주 ≈ 4년
      case '1M': return 200;   // 200개월 ≈ 16년
      default: return 200;
    }
  };
  
  // 시간봉별 차트 범위 설명
  const getChartRangeDescription = (tf: string): string => {
    switch (tf.toLowerCase()) {
      case '1m': return '최근 5시간';
      case '3m': return '최근 15시간';
      case '5m': return '최근 25시간';
      case '10m': return '최근 33시간';
      case '15m': return '최근 50시간';
      case '30m': return '최근 100시간 (약 4일)';
      case '1h': return '최근 200시간 (약 8일)';
      case '4h': return '최근 800시간 (약 33일)';
      case '1d': return '최근 200일 (약 6개월)';
      case '1w': return '최근 200주 (약 4년)';
      case '1M': return '최근 200개월';
      default: return '최근 200개';
    }
  };

  // 검색 결과 더블클릭 시 차트 표시
  const handleResultDoubleClick = async (result: PatternMatchResult) => {
    setSelectedSymbol(result);
    setCenterTab(1); // 차트 탭으로 전환
    setIsLoadingChart(true);
    
    try {
      const candleCount = getCandleCountForChart(timeframe);
      const response = await fetchCandleData(result.symbol, timeframe, candleCount);
      if (response.success && response.data.length > 0) {
        // CandleDataForChart를 CandleData로 변환
        const convertedData: CandleData[] = response.data.map(candle => ({
          time: candle.time,
          open: candle.open,
          high: candle.high,
          low: candle.low,
          close: candle.close,
          volume: candle.volume || 0,
        }));
        setChartData(convertedData);
      } else {
        setError('차트 데이터를 불러올 수 없습니다.');
      }
    } catch (err) {
      console.error('차트 데이터 로드 실패:', err);
      setError('차트 데이터 로드 중 오류가 발생했습니다.');
    } finally {
      setIsLoadingChart(false);
    }
  };
  
  // 스타일
  const panelStyle = {
    bgcolor: isDark ? '#18181b' : '#ffffff',
    borderColor: isDark ? '#27272a' : '#e0e0e0',
  };
  
  const cardStyle = {
    bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
    border: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
  };

  return (
    <Grid container spacing={2}>
      {/* 상단 툴바 카드 */}
      <Grid item xs={12}>
        <Paper elevation={3} sx={{ p: 2 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <SearchIcon sx={{ fontSize: 24, color: '#3b82f6' }} />
              <Typography variant="h6" sx={{ fontWeight: 600 }}>
                패턴검색
              </Typography>
              {selectedPattern && (
                <Chip 
                  label={selectedPattern.name} 
                  size="small" 
                  color="primary"
                  onDelete={() => setSelectedPattern(null)}
                />
              )}
            </Box>
            <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}>
              {/* 시간봉 선택 */}
              <FormControl size="small" sx={{ minWidth: 90 }}>
                <Select
                  value={timeframe}
                  onChange={(e) => setTimeframe(e.target.value)}
                  sx={{ fontSize: '12px' }}
                >
                  <MenuItem value="1m">1분봉</MenuItem>
                  <MenuItem value="5m">5분봉</MenuItem>
                  <MenuItem value="15m">15분봉</MenuItem>
                  <MenuItem value="1h">1시간봉</MenuItem>
                  <MenuItem value="4h">4시간봉</MenuItem>
                  <MenuItem value="1d">일봉</MenuItem>
                  <MenuItem value="1w">주봉</MenuItem>
                </Select>
              </FormControl>
              {/* 유사도 */}
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: 120 }}>
                <Typography sx={{ fontSize: '11px', color: 'text.secondary', whiteSpace: 'nowrap' }}>
                  유사도
                </Typography>
                <Slider
                  value={minSimilarity}
                  onChange={(_, v) => setMinSimilarity(v as number)}
                  min={50}
                  max={100}
                  size="small"
                  sx={{ width: 80 }}
                />
                <Typography sx={{ fontSize: '11px', color: 'text.secondary', minWidth: 28 }}>
                  {minSimilarity}%
                </Typography>
              </Box>
              <Button
                variant="contained"
                size="small"
                startIcon={isSearching ? <CircularProgress size={14} color="inherit" /> : <SearchIcon />}
                onClick={handleSearch}
                disabled={isSearching || (drawnPatternData.length === 0 && !selectedPattern)}
              >
                검색
              </Button>
              <Button
                variant="outlined"
                size="small"
                onClick={handleReset}
              >
                초기화
              </Button>
            </Box>
          </Box>
        </Paper>
      </Grid>

      {/* 3컬럼 레이아웃 */}
      <Grid item xs={12}>
        <Box sx={{
          display: 'grid',
          gridTemplateColumns: { xs: '1fr', md: '300px 1fr 340px' },
          height: 'calc(100vh - 280px)',
          minHeight: 500,
          gap: 2,
        }}>
          {/* 왼쪽 패널 - 패턴 라이브러리 */}
          <Paper elevation={2} sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 헤더 + 탭 */}
            <Box sx={{ 
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
            }}>
              <Tabs 
                value={libraryTab} 
                onChange={(_, v) => setLibraryTab(v)}
                sx={{
                  minHeight: 36,
                  '& .MuiTab-root': {
                    minHeight: 36,
                    fontSize: '11px',
                    fontWeight: 600,
                    textTransform: 'none',
                    py: 0.5,
                  },
                }}
              >
                <Tab label="📈 추세패턴" />
                <Tab label="🕯️ 캔들패턴" />
              </Tabs>
            </Box>
        
        {/* 검색 */}
        <Box sx={{ p: 1.5, borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}` }}>
          <TextField
            fullWidth
            size="small"
            placeholder="패턴 검색..."
            value={patternSearch}
            onChange={(e) => setPatternSearch(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon sx={{ fontSize: 18, color: isDark ? '#71717a' : '#9ca3af' }} />
                </InputAdornment>
              ),
            }}
            sx={{
              '& .MuiOutlinedInput-root': {
                bgcolor: isDark ? '#27272a' : '#f5f5f5',
                fontSize: '13px',
              },
            }}
          />
        </Box>
        
        {/* 패턴 목록 */}
        <Box sx={{ flex: 1, overflow: 'auto', p: 1.5 }}>
          {/* 추세패턴 탭 */}
          {libraryTab === 0 && (
            <>
              {/* 반전 패턴 */}
              {groupedTemplates.REVERSAL.length > 0 && (
                <Box sx={{ mb: 2 }}>
                  <Box sx={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    gap: 1, 
                    px: 1, 
                    py: 0.5,
                    mb: 1,
                  }}>
                    <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', textTransform: 'uppercase' }}>
                      🔄 반전 패턴
                    </Typography>
                    <Chip label={groupedTemplates.REVERSAL.length} size="small" sx={{ height: 18, fontSize: '10px' }} />
                  </Box>
                  <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1 }}>
                    {groupedTemplates.REVERSAL.map(pattern => (
                      <PatternCard 
                        key={pattern.id} 
                        pattern={pattern} 
                        isSelected={selectedPattern?.id === pattern.id}
                        onClick={() => handlePatternSelect(pattern)}
                        isDark={isDark}
                      />
                    ))}
                  </Box>
                </Box>
              )}
              
              {/* 지속 패턴 */}
              {groupedTemplates.CONTINUATION.length > 0 && (
                <Box sx={{ mb: 2 }}>
                  <Box sx={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    gap: 1, 
                    px: 1, 
                    py: 0.5,
                    mb: 1,
                  }}>
                    <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', textTransform: 'uppercase' }}>
                      ➡️ 지속 패턴
                    </Typography>
                    <Chip label={groupedTemplates.CONTINUATION.length} size="small" sx={{ height: 18, fontSize: '10px' }} />
                  </Box>
                  <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1 }}>
                    {groupedTemplates.CONTINUATION.map(pattern => (
                      <PatternCard 
                        key={pattern.id} 
                        pattern={pattern} 
                        isSelected={selectedPattern?.id === pattern.id}
                        onClick={() => handlePatternSelect(pattern)}
                        isDark={isDark}
                      />
                    ))}
                  </Box>
                </Box>
              )}
            </>
          )}
          
          {/* 캔들패턴 탭 */}
          {libraryTab === 1 && (
            <>
              {groupedTemplates.CANDLE.length > 0 ? (
                <Box>
                  <Box sx={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    gap: 1, 
                    px: 1, 
                    py: 0.5,
                    mb: 1,
                  }}>
                    <Typography sx={{ fontSize: '11px', fontWeight: 600, color: isDark ? '#a1a1aa' : '#666', textTransform: 'uppercase' }}>
                      🕯️ 캔들스틱 패턴
                    </Typography>
                    <Chip label={groupedTemplates.CANDLE.length} size="small" sx={{ height: 18, fontSize: '10px' }} />
                  </Box>
                  <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1 }}>
                    {groupedTemplates.CANDLE.map(pattern => (
                      <CandlePatternCard 
                        key={pattern.id} 
                        pattern={pattern} 
                        isSelected={selectedPattern?.id === pattern.id}
                        onClick={() => handlePatternSelect(pattern)}
                        isDark={isDark}
                      />
                    ))}
                  </Box>
                </Box>
              ) : (
                <Box sx={{ textAlign: 'center', py: 4 }}>
                  <Typography sx={{ fontSize: '32px', mb: 1 }}>🕯️</Typography>
                  <Typography sx={{ fontSize: '12px', color: isDark ? '#52525b' : '#999' }}>
                    캔들 패턴이 없습니다
                  </Typography>
                </Box>
              )}
            </>
          )}
            </Box>
          </Paper>
      
          {/* 중앙 패널 - 차트/그리기 영역 */}
          <Paper elevation={2} sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 메인 탭 (패턴입력 / 차트) */}
            <Box sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              px: 1.5,
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
            }}>
              <Tabs 
                value={centerTab} 
                onChange={(_, v) => setCenterTab(v)}
                sx={{
                  minHeight: 40,
                  '& .MuiTab-root': {
                    minHeight: 40,
                    fontSize: '12px',
                    fontWeight: 600,
                    textTransform: 'none',
                  },
                }}
              >
                <Tab label="📝 패턴입력" />
                <Tab 
                  label={selectedSymbol ? `📊 ${selectedSymbol.symbol}` : "📊 차트"} 
                  disabled={!selectedSymbol}
                />
              </Tabs>
            </Box>
        
        {/* 패턴입력 탭 하위 탭 */}
        {centerTab === 0 && (
          <Box sx={{
            display: 'flex',
            alignItems: 'center',
            px: 1.5,
            py: 0.5,
            borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
            bgcolor: isDark ? '#1a1a1f' : '#fafafa',
          }}>
            <Tabs 
              value={activeTab} 
              onChange={(_, v) => setActiveTab(v)}
              sx={{
                minHeight: 32,
                '& .MuiTab-root': {
                  minHeight: 32,
                  fontSize: '11px',
                  textTransform: 'none',
                  py: 0.5,
                },
              }}
            >
              <Tab label="직접 그리기" />
              <Tab label="패턴 선택" />
              <Tab label="이미지 업로드" />
            </Tabs>
          </Box>
        )}
        
        {/* 패턴입력 탭 내용 */}
        {centerTab === 0 && (
          <>
            {/* 차트 헤더 */}
            <Box sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'space-between',
              p: 2,
            }}>
              <Box>
                <Typography sx={{ fontSize: '16px', fontWeight: 600 }}>
                  패턴 입력
                </Typography>
                <Typography sx={{ fontSize: '12px', color: isDark ? '#71717a' : '#888' }}>
                  {activeTab === 0 && '원하는 패턴을 그리거나 왼쪽에서 선택하세요'}
                  {activeTab === 1 && '왼쪽 패널에서 패턴을 선택하세요'}
                  {activeTab === 2 && '차트 이미지를 업로드하세요'}
                </Typography>
              </Box>
              
              {selectedPattern && (
                <Chip
                  label={selectedPattern.name}
                  onDelete={() => setSelectedPattern(null)}
                  color="primary"
                  size="small"
                />
              )}
            </Box>
            
            {/* 캔버스 영역 */}
            <Box sx={{ 
              flex: 1, 
              m: 2, 
              mt: 0,
              borderRadius: 2,
              border: `2px dashed ${isDark ? '#3f3f46' : '#d0d0d0'}`,
              overflow: 'hidden',
              bgcolor: isDark ? '#0f0f14' : '#fafafa',
            }}>
              {activeTab === 0 && (
                <PatternCanvas
                  isDark={isDark}
                  onPatternChange={handlePatternDraw}
                  templatePattern={selectedPattern?.data}
                />
              )}
              
              {activeTab === 1 && (
                <Box sx={{ 
                  height: '100%', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  flexDirection: 'column',
                  gap: 2,
                }}>
                  {selectedPattern ? (
                    <>
                      <PatternPreview pattern={selectedPattern} isDark={isDark} />
                      <Typography sx={{ fontSize: '14px', fontWeight: 600 }}>
                        {selectedPattern.name}
                      </Typography>
                      <Typography sx={{ fontSize: '12px', color: isDark ? '#71717a' : '#888', textAlign: 'center', maxWidth: 400 }}>
                        {selectedPattern.description}
                      </Typography>
                    </>
                  ) : (
                    <>
                      <Typography sx={{ fontSize: '32px' }}>📊</Typography>
                      <Typography sx={{ fontSize: '14px', color: isDark ? '#52525b' : '#9ca3af' }}>
                        왼쪽 패널에서 패턴을 선택하세요
                      </Typography>
                    </>
                  )}
                </Box>
              )}
              
              {activeTab === 2 && (
                <Box sx={{ 
                  height: '100%', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  flexDirection: 'column',
                  gap: 2,
                }}>
                  <UploadIcon sx={{ fontSize: 48, color: isDark ? '#3f3f46' : '#d0d0d0' }} />
                  <Typography sx={{ fontSize: '14px', color: isDark ? '#52525b' : '#9ca3af' }}>
                    차트 이미지를 드래그하거나 클릭하여 업로드
                  </Typography>
                  <Button variant="outlined" size="small">
                    파일 선택
                  </Button>
                </Box>
              )}
            </Box>
          </>
        )}
        
        {/* 차트 탭 내용 */}
        {centerTab === 1 && (
          <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 차트 헤더 */}
            <Box sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'space-between',
              p: 2,
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
            }}>
              <Box>
                <Typography sx={{ fontSize: '16px', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box sx={{
                    width: 32,
                    height: 32,
                    borderRadius: '50%',
                    background: 'linear-gradient(135deg, #f59e0b, #d97706)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '14px',
                    fontWeight: 700,
                    color: '#fff',
                  }}>
                    {selectedSymbol?.symbol.split('-')[1]?.charAt(0) || 'C'}
                  </Box>
                  {selectedSymbol?.symbol}
                  <Chip 
                    label={selectedSymbol?.name} 
                    size="small" 
                    sx={{ ml: 1, height: 22, fontSize: '11px' }}
                  />
                </Typography>
                <Typography sx={{ fontSize: '12px', color: isDark ? '#71717a' : '#888', mt: 0.5 }}>
                  유사도: <strong style={{ color: '#22c55e' }}>{selectedSymbol?.similarity}%</strong>
                  {' | '}시간봉: {timeframe}
                  {' | '}범위: {getChartRangeDescription(timeframe)}
                  {' | '}예상 수익: <strong style={{ color: selectedSymbol && selectedSymbol.expectedReturn >= 0 ? '#22c55e' : '#ef4444' }}>
                    {selectedSymbol && selectedSymbol.expectedReturn >= 0 ? '+' : ''}{selectedSymbol?.expectedReturn}%
                  </strong>
                </Typography>
              </Box>
              
              <Button
                variant="outlined"
                size="small"
                onClick={() => setCenterTab(0)}
                sx={{ fontSize: '12px' }}
              >
                패턴입력으로 돌아가기
              </Button>
            </Box>
            
            {/* 캔들스틱 차트 */}
            <Box sx={{ flex: 1, p: 2, minHeight: 400 }}>
              {isLoadingChart ? (
                <Box sx={{ 
                  height: '100%', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  flexDirection: 'column',
                  gap: 2,
                }}>
                  <CircularProgress />
                  <Typography sx={{ fontSize: '13px', color: isDark ? '#a1a1aa' : '#666' }}>
                    차트 데이터 로딩 중...
                  </Typography>
                </Box>
              ) : chartData.length > 0 ? (
                <CandlestickChart
                  data={chartData}
                  height={Math.max(400, window.innerHeight - 350)}
                />
              ) : (
                <Box sx={{ 
                  height: '100%', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  flexDirection: 'column',
                  gap: 2,
                }}>
                  <Typography sx={{ fontSize: '32px' }}>📊</Typography>
                  <Typography sx={{ fontSize: '14px', color: isDark ? '#52525b' : '#9ca3af' }}>
                    차트 데이터가 없습니다
                  </Typography>
                </Box>
              )}
            </Box>
              </Box>
            )}
          </Paper>
      
          {/* 오른쪽 패널 - 검색 결과 */}
          <Paper elevation={2} sx={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 헤더 */}
            <Box sx={{ 
              p: 1.5, 
              borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              bgcolor: isDark ? '#1f1f26' : '#f5f5f5',
            }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Typography sx={{ fontSize: '13px', fontWeight: 600 }}>
                  🎯 검색 결과
                </Typography>
                {results.length > 0 && (
                  <Chip 
                    label={`${results.length}개`} 
                    size="small" 
                    color="success"
                    sx={{ height: 20, fontSize: '11px' }}
                  />
                )}
              </Box>
          
              <FormControl size="small" sx={{ minWidth: 90 }}>
                <Select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value as any)}
                  sx={{ fontSize: '11px', height: 28 }}
                >
                  <MenuItem value="similarity">유사도순</MenuItem>
                  <MenuItem value="expectedReturn">수익률순</MenuItem>
                  <MenuItem value="successRate">성공률순</MenuItem>
                </Select>
              </FormControl>
            </Box>
        
        {/* 안내 메시지 */}
        {results.length > 0 && (
          <Box sx={{ 
            px: 1.5, 
            py: 0.75, 
            bgcolor: isDark ? 'rgba(34,197,94,0.1)' : 'rgba(34,197,94,0.05)',
            borderBottom: `1px solid ${isDark ? '#27272a' : '#e0e0e0'}`,
          }}>
            <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888' }}>
              💡 더블클릭하여 차트 보기 | {timeframe} 기준
            </Typography>
          </Box>
        )}
        
        {/* 결과 목록 */}
        <Box sx={{ flex: 1, overflow: 'auto', p: 1 }}>
          {error && (
            <Alert severity="error" sx={{ mb: 1, py: 0.5 }}>
              {error}
            </Alert>
          )}
          
          {isSearching ? (
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', py: 4 }}>
              <CircularProgress size={36} />
              <Typography sx={{ mt: 2, fontSize: '12px', color: isDark ? '#a1a1aa' : '#666' }}>
                업비트 전 종목 데이터 조회 중...
              </Typography>
            </Box>
          ) : sortedResults.length > 0 ? (
            sortedResults.map((result, index) => (
              <ResultCard 
                key={`${result.symbol}-${index}`} 
                result={result} 
                isDark={isDark} 
                onDoubleClick={() => handleResultDoubleClick(result)}
                isSelected={selectedSymbol?.symbol === result.symbol}
              />
            ))
          ) : (
            <Box sx={{ textAlign: 'center', py: 4 }}>
              <Typography sx={{ fontSize: '28px', mb: 1 }}>🔍</Typography>
              <Typography sx={{ fontSize: '12px', color: isDark ? '#52525b' : '#999' }}>
                패턴을 선택 후 검색
              </Typography>
            </Box>
            )}
          </Box>
          </Paper>
        </Box>
      </Grid>
    </Grid>
  );
};

// 패턴 카드 컴포넌트
interface PatternCardProps {
  pattern: PatternTemplate;
  isSelected: boolean;
  onClick: () => void;
  isDark: boolean;
}

const PatternCard: React.FC<PatternCardProps> = ({ pattern, isSelected, onClick, isDark }) => {
  return (
    <Box
      onClick={onClick}
      sx={{
        p: 1.5,
        borderRadius: 1,
        border: `1px solid ${isSelected ? '#22c55e' : (isDark ? '#27272a' : '#e0e0e0')}`,
        bgcolor: isSelected ? 'rgba(34,197,94,0.1)' : (isDark ? '#1f1f26' : '#f5f5f5'),
        cursor: 'pointer',
        transition: 'all 0.2s',
        '&:hover': {
          borderColor: '#3b82f6',
          bgcolor: isDark ? '#252530' : '#f0f0f0',
        },
      }}
    >
      {/* 미니 차트 */}
      <Box sx={{ 
        height: 40, 
        bgcolor: isDark ? '#27272a' : '#e0e0e0', 
        borderRadius: 0.5, 
        mb: 1,
        overflow: 'hidden',
      }}>
        <svg viewBox="0 0 100 40" style={{ width: '100%', height: '100%' }}>
          <path
            d={generateSvgPath(pattern.data)}
            stroke={pattern.direction === 'BULLISH' ? '#22c55e' : pattern.direction === 'BEARISH' ? '#ef4444' : '#f59e0b'}
            strokeWidth="2"
            fill="none"
          />
        </svg>
      </Box>
      <Typography sx={{ fontSize: '11px', fontWeight: 500, textAlign: 'center', color: isDark ? '#d4d4d8' : '#333' }}>
        {pattern.name}
      </Typography>
    </Box>
  );
};

// 캔들 패턴 카드 컴포넌트
const CandlePatternCard: React.FC<PatternCardProps> = ({ pattern, isSelected, onClick, isDark }) => {
  // 캔들스틱 패턴 SVG 생성
  const renderCandlePattern = () => {
    const candleData = pattern.candleData || [];
    if (candleData.length === 0) {
      // 기본 라인 차트로 표시
      return (
        <path
          d={generateSvgPath(pattern.data)}
          stroke={pattern.direction === 'BULLISH' ? '#22c55e' : pattern.direction === 'BEARISH' ? '#ef4444' : '#f59e0b'}
          strokeWidth="2"
          fill="none"
        />
      );
    }
    
    // 캔들스틱 렌더링
    const candleWidth = 8;
    const candleSpacing = candleData.length > 1 ? (100 - candleWidth * candleData.length) / (candleData.length + 1) : 40;
    
    return candleData.map((candle, idx) => {
      const x = candleSpacing + idx * (candleWidth + candleSpacing);
      const isBullish = candle.close >= candle.open;
      const color = isBullish ? '#22c55e' : '#ef4444';
      
      // 정규화 (0-1 범위의 값을 40 높이에 맞춤)
      const scaleY = (val: number) => 38 - val * 34;
      
      const bodyTop = scaleY(Math.max(candle.open, candle.close));
      const bodyBottom = scaleY(Math.min(candle.open, candle.close));
      const bodyHeight = Math.max(bodyBottom - bodyTop, 1);
      
      return (
        <g key={idx}>
          {/* 위꼬리 */}
          <line
            x1={x + candleWidth / 2}
            y1={scaleY(candle.high)}
            x2={x + candleWidth / 2}
            y2={bodyTop}
            stroke={color}
            strokeWidth="1"
          />
          {/* 아래꼬리 */}
          <line
            x1={x + candleWidth / 2}
            y1={bodyBottom}
            x2={x + candleWidth / 2}
            y2={scaleY(candle.low)}
            stroke={color}
            strokeWidth="1"
          />
          {/* 몸통 */}
          <rect
            x={x}
            y={bodyTop}
            width={candleWidth}
            height={bodyHeight}
            fill={isBullish ? color : color}
            stroke={color}
            strokeWidth="1"
          />
        </g>
      );
    });
  };

  return (
    <Box
      onClick={onClick}
      sx={{
        p: 1.5,
        borderRadius: 1,
        border: `1px solid ${isSelected ? '#22c55e' : (isDark ? '#27272a' : '#e0e0e0')}`,
        bgcolor: isSelected ? 'rgba(34,197,94,0.1)' : (isDark ? '#1f1f26' : '#f5f5f5'),
        cursor: 'pointer',
        transition: 'all 0.2s',
        '&:hover': {
          borderColor: '#3b82f6',
          bgcolor: isDark ? '#252530' : '#f0f0f0',
        },
      }}
    >
      {/* 캔들 패턴 미리보기 */}
      <Box sx={{ 
        height: 50, 
        bgcolor: isDark ? '#27272a' : '#e0e0e0', 
        borderRadius: 0.5, 
        mb: 1,
        overflow: 'hidden',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
        <svg viewBox="0 0 100 40" style={{ width: '100%', height: '100%' }}>
          {renderCandlePattern()}
        </svg>
      </Box>
      <Typography sx={{ fontSize: '10px', fontWeight: 500, textAlign: 'center', color: isDark ? '#d4d4d8' : '#333', lineHeight: 1.2 }}>
        {pattern.name}
      </Typography>
      {pattern.successRate && (
        <Typography sx={{ fontSize: '9px', textAlign: 'center', color: pattern.direction === 'BULLISH' ? '#22c55e' : '#ef4444', mt: 0.25 }}>
          {pattern.successRate}% 반전
        </Typography>
      )}
    </Box>
  );
};

// 패턴 미리보기 컴포넌트
interface PatternPreviewProps {
  pattern: PatternTemplate;
  isDark: boolean;
}

const PatternPreview: React.FC<PatternPreviewProps> = ({ pattern, isDark }) => {
  return (
    <Box sx={{ 
      width: 400, 
      height: 200, 
      bgcolor: isDark ? '#27272a' : '#e0e0e0', 
      borderRadius: 2,
      p: 2,
    }}>
      <svg viewBox="0 0 360 160" style={{ width: '100%', height: '100%' }}>
        {/* 그리드 */}
        <defs>
          <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
            <path d="M 40 0 L 0 0 0 40" fill="none" stroke={isDark ? '#3f3f46' : '#d0d0d0'} strokeWidth="0.5"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#grid)"/>
        
        {/* 패턴 라인 */}
        <path
          d={generateSvgPath(pattern.data, 360, 160, 20)}
          stroke={pattern.direction === 'BULLISH' ? '#22c55e' : pattern.direction === 'BEARISH' ? '#ef4444' : '#f59e0b'}
          strokeWidth="3"
          fill="none"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </Box>
  );
};

// 결과 카드 컴포넌트 (컴팩트 버전)
interface ResultCardProps {
  result: PatternMatchResult;
  isDark: boolean;
  onDoubleClick?: () => void;
  isSelected?: boolean;
}

const ResultCard: React.FC<ResultCardProps> = ({ result, isDark, onDoubleClick, isSelected }) => {
  return (
    <Box 
      onDoubleClick={onDoubleClick}
      sx={{
        p: 1,
        mb: 0.75,
        borderRadius: 1,
        border: `1px solid ${isSelected ? '#3b82f6' : (isDark ? '#27272a' : '#e0e0e0')}`,
        bgcolor: isSelected ? (isDark ? 'rgba(59, 130, 246, 0.15)' : 'rgba(59, 130, 246, 0.1)') : (isDark ? '#1f1f26' : '#f5f5f5'),
        cursor: 'pointer',
        transition: 'all 0.15s',
        '&:hover': {
          borderColor: '#3b82f6',
          bgcolor: isDark ? 'rgba(59, 130, 246, 0.1)' : 'rgba(59, 130, 246, 0.05)',
        },
      }}
    >
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        {/* 심볼 아이콘 */}
        <Box sx={{
          width: 28,
          height: 28,
          borderRadius: '50%',
          background: result.direction === 'BULLISH' 
            ? 'linear-gradient(135deg, #22c55e, #16a34a)' 
            : result.direction === 'BEARISH' 
            ? 'linear-gradient(135deg, #ef4444, #dc2626)'
            : 'linear-gradient(135deg, #f59e0b, #d97706)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '11px',
          fontWeight: 700,
          color: '#fff',
          flexShrink: 0,
        }}>
          {result.symbol.split('-')[1]?.charAt(0) || 'C'}
        </Box>
        
        {/* 종목 정보 */}
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <Typography sx={{ fontSize: '12px', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {result.symbol.split('-')[1]}
            </Typography>
            <Typography sx={{ fontSize: '10px', color: isDark ? '#71717a' : '#888', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {result.name}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.25 }}>
            <Typography sx={{ 
              fontSize: '10px', 
              color: result.expectedReturn >= 0 ? '#22c55e' : '#ef4444',
              fontWeight: 500,
            }}>
              {result.expectedReturn >= 0 ? '▲' : '▼'}{Math.abs(result.expectedReturn)}%
            </Typography>
            <Typography sx={{ fontSize: '10px', color: isDark ? '#52525b' : '#999' }}>
              {result.expectedPeriod}
            </Typography>
          </Box>
        </Box>
        
        {/* 유사도 */}
        <Box sx={{ 
          textAlign: 'right',
          flexShrink: 0,
        }}>
          <Typography sx={{ 
            fontSize: '16px', 
            fontWeight: 700, 
            color: result.similarity >= 80 ? '#22c55e' : result.similarity >= 70 ? '#f59e0b' : '#a1a1aa',
            lineHeight: 1,
          }}>
            {result.similarity}%
          </Typography>
        </Box>
      </Box>
    </Box>
  );
};

// SVG 경로 생성 헬퍼
const generateSvgPath = (data: number[], width = 100, height = 40, padding = 5): string => {
  if (!data || data.length < 2) return '';
  
  const drawWidth = width - padding * 2;
  const drawHeight = height - padding * 2;
  
  return data.map((value, index) => {
    const x = padding + (index / (data.length - 1)) * drawWidth;
    const y = padding + (1 - value) * drawHeight;
    return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
  }).join(' ');
};

const generateSvgPathFromData = (data: number[]): string => {
  if (!data || data.length < 2) return '';
  
  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = max - min || 1;
  
  return data.map((value, index) => {
    const x = 10 + (index / (data.length - 1)) * 300;
    const y = 5 + (1 - (value - min) / range) * 50;
    return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
  }).join(' ');
};

export default PatternSearchPage;

