import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Chip,
  useTheme,
  Tabs,
  Tab,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  Divider,
  Badge,
} from '@mui/material';
import {
  AccountTree as TreeIcon,
  ShowChart as ChartIcon,
  TrendingUp as TrendingUpIcon,
  TrendingDown as TrendingDownIcon,
  ExpandMore as ExpandMoreIcon,
  TouchApp as TouchAppIcon,
  AutoAwesome as AutoAwesomeIcon,
} from '@mui/icons-material';
import { useDraggable } from '@dnd-kit/core';
import { 
  TEMPLATE_CATEGORIES, 
  StrategyTemplate, 
  loadCustomTemplates,
  TemplateCategory,
  getDynamicTemplateName,
  getDynamicTemplateDescription,
  MASettings
} from './strategyTemplates';
import { useIndicatorVisibility } from '../../contexts/IndicatorVisibilityContext';

// ============================================================
// 타입 정의
// ============================================================

interface PaletteItem {
  id: string;
  type: 'operator' | 'indicator';
  label: string;
  value: string;
  icon?: React.ReactNode;
  description?: string;
  color?: string;
}

// ============================================================
// 드래그 가능한 팔레트 아이템 컴포넌트
// ============================================================

interface DraggableItemProps {
  item: PaletteItem;
}

const DraggableItem: React.FC<DraggableItemProps> = ({ item }) => {
  const theme = useTheme();
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
    id: item.id,
    data: {
      type: item.type,
      value: item.value,
      label: item.label,
    },
  });

  return (
    <Box
      ref={setNodeRef}
      {...listeners}
      {...attributes}
      sx={{ display: 'inline-block' }}
    >
      <Chip
        label={
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            {item.icon}
            {item.label}
          </Box>
        }
        sx={{
          m: 0.5,
          cursor: isDragging ? 'grabbing' : 'grab',
          opacity: isDragging ? 0.5 : 1,
          backgroundColor: item.color || theme.palette.primary.main,
          color: theme.palette.primary.contrastText,
          '&:hover': {
            backgroundColor: item.color ? 
              theme.palette.mode === 'dark' ? 
                theme.palette.grey[700] : 
                theme.palette.grey[300] : 
              theme.palette.primary.dark,
          },
          fontWeight: 'bold',
          fontSize: '0.9rem',
        }}
      />
    </Box>
  );
};

// ============================================================
// NodePalette 메인 컴포넌트
// ============================================================

interface NodePaletteProps {
  disabled?: boolean;
  onTemplateSelect?: (template: StrategyTemplate) => void;
}

const NodePalette: React.FC<NodePaletteProps> = ({ disabled = false, onTemplateSelect }) => {
  const theme = useTheme();
  const { settings: visibilitySettings } = useIndicatorVisibility();
  const [currentTab, setCurrentTab] = useState<'manual' | 'auto'>('manual');
  const [customTemplates, setCustomTemplates] = useState<StrategyTemplate[]>([]);
  const [allCategories, setAllCategories] = useState<TemplateCategory[]>([]);
  
  // MA 설정 정보 (동적 라벨 생성용)
  const maSettings: MASettings = {
    maLines: visibilitySettings.maLines || []
  };

  // 사용자 정의 템플릿 로드
  useEffect(() => {
    loadTemplates();
    
    // 템플릿 저장 이벤트 리스너 등록
    const handleTemplateSaved = () => {
      console.log('📥 템플릿 저장 이벤트 감지 - 목록 새로고침');
      loadTemplates();
    };
    
    window.addEventListener('templateSaved', handleTemplateSaved);
    
    return () => {
      window.removeEventListener('templateSaved', handleTemplateSaved);
    };
  }, []);

  // 템플릿 로드 함수
  const loadTemplates = () => {
    const customs = loadCustomTemplates();
    setCustomTemplates(customs);
    
    // 기본 카테고리와 사용자 정의 템플릿 합치기
    const categoriesMap = new Map<string, TemplateCategory>();
    
    // 기본 카테고리 추가
    TEMPLATE_CATEGORIES.forEach(cat => {
      categoriesMap.set(cat.id, { ...cat });
    });
    
    // 사용자 정의 템플릿을 해당 카테고리에 추가
    customs.forEach(template => {
      const categoryId = template.category;
      if (categoriesMap.has(categoryId)) {
        const category = categoriesMap.get(categoryId)!;
        category.templates = [...category.templates, template];
      } else {
        // 새로운 카테고리 생성 (사용자 정의)
        categoriesMap.set(categoryId, {
          id: categoryId,
          label: template.categoryLabel,
          icon: '⭐',
          templates: [template],
        });
      }
    });
    
    setAllCategories(Array.from(categoriesMap.values()));
  };

  // 자동설정 탭이 열릴 때마다 템플릿 새로고침
  useEffect(() => {
    if (currentTab === 'auto') {
      loadTemplates();
    }
  }, [currentTab]);

  // 논리 연산자
  const operators: PaletteItem[] = [
    {
      id: 'operator-and',
      type: 'operator',
      label: 'AND (그리고)',
      value: 'AND',
      icon: <TreeIcon fontSize="small" />,
      description: '모든 자식 조건을 만족해야 함',
      color: theme.palette.success.main,
    },
    {
      id: 'operator-or',
      type: 'operator',
      label: 'OR (또는)',
      value: 'OR',
      icon: <TreeIcon fontSize="small" />,
      description: '자식 조건 중 하나 이상 만족하면 됨',
      color: theme.palette.info.main,
    },
    {
      id: 'operator-not',
      type: 'operator',
      label: 'NOT (반대)',
      value: 'NOT',
      icon: <TreeIcon fontSize="small" />,
      description: '자식 조건의 반대',
      color: theme.palette.warning.main,
    },
  ];

  // 이동평균 지표들
  const movingAverages: PaletteItem[] = [
    {
      id: 'indicator-ma',
      type: 'indicator',
      label: 'MA (이동평균)',
      value: 'MA',
      icon: <TrendingUpIcon fontSize="small" />,
      description: 'Moving Average',
      color: theme.palette.primary.main,
    },
    {
      id: 'indicator-ema',
      type: 'indicator',
      label: 'EMA (지수이동평균)',
      value: 'EMA',
      icon: <TrendingUpIcon fontSize="small" />,
      description: 'Exponential Moving Average',
      color: theme.palette.primary.main,
    },
    {
      id: 'indicator-bollinger',
      type: 'indicator',
      label: '볼린저밴드',
      value: 'BOLLINGER',
      icon: <ChartIcon fontSize="small" />,
      description: 'Bollinger Bands',
      color: theme.palette.primary.main,
    },
    {
      id: 'indicator-ichimoku',
      type: 'indicator',
      label: '일목균형표',
      value: 'ICHIMOKU',
      icon: <ChartIcon fontSize="small" />,
      description: 'Ichimoku Cloud',
      color: theme.palette.primary.main,
    },
  ];

  // 보조지표들 (16가지)
  const indicators: PaletteItem[] = [
    {
      id: 'indicator-new-psychological',
      type: 'indicator',
      label: '신심리도',
      value: 'NEW_PSYCHOLOGICAL',
      icon: <ChartIcon fontSize="small" />,
      description: 'New Psychological Line',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-invest-psychological',
      type: 'indicator',
      label: '투자심리도',
      value: 'INVEST_PSYCHOLOGICAL',
      icon: <ChartIcon fontSize="small" />,
      description: 'Investor Psychological Line',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-macd',
      type: 'indicator',
      label: 'MACD',
      value: 'MACD',
      icon: <ChartIcon fontSize="small" />,
      description: 'Moving Average Convergence Divergence',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-cci',
      type: 'indicator',
      label: 'CCI',
      value: 'CCI',
      icon: <ChartIcon fontSize="small" />,
      description: 'Commodity Channel Index',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-adx',
      type: 'indicator',
      label: 'ADX',
      value: 'ADX',
      icon: <TrendingUpIcon fontSize="small" />,
      description: 'Average Directional Index',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-bwi',
      type: 'indicator',
      label: 'BWI',
      value: 'BWI',
      icon: <ChartIcon fontSize="small" />,
      description: 'Bollinger Band Width Index',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-dmi',
      type: 'indicator',
      label: 'DMI',
      value: 'DMI',
      icon: <ChartIcon fontSize="small" />,
      description: 'Directional Movement Index',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-obv',
      type: 'indicator',
      label: 'OBV',
      value: 'OBV',
      icon: <ChartIcon fontSize="small" />,
      description: 'On Balance Volume',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-rsi',
      type: 'indicator',
      label: 'RSI',
      value: 'RSI',
      icon: <TrendingUpIcon fontSize="small" />,
      description: 'Relative Strength Index',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-stochastic',
      type: 'indicator',
      label: 'Stochastic',
      value: 'STOCHASTIC',
      icon: <ChartIcon fontSize="small" />,
      description: 'Stochastic Slow',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-williams-r',
      type: 'indicator',
      label: 'Williams %R',
      value: 'WILLIAMS_R',
      icon: <ChartIcon fontSize="small" />,
      description: 'Williams Percent Range',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-trix',
      type: 'indicator',
      label: 'TRIX',
      value: 'TRIX',
      icon: <ChartIcon fontSize="small" />,
      description: 'Triple Exponential Moving Average',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-volume-osc',
      type: 'indicator',
      label: 'VolumeOSC',
      value: 'VOLUME_OSC',
      icon: <ChartIcon fontSize="small" />,
      description: 'Volume Oscillator',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-vr',
      type: 'indicator',
      label: 'VR',
      value: 'VR',
      icon: <ChartIcon fontSize="small" />,
      description: 'Volume Ratio',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-disparity',
      type: 'indicator',
      label: '이격도',
      value: 'DISPARITY',
      icon: <ChartIcon fontSize="small" />,
      description: 'Disparity Index',
      color: theme.palette.secondary.main,
    },
    {
      id: 'indicator-volume',
      type: 'indicator',
      label: '거래량',
      value: 'VOLUME',
      icon: <ChartIcon fontSize="small" />,
      description: 'Trading Volume',
      color: theme.palette.secondary.main,
    },
  ];

  return (
    <Box
      sx={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        opacity: disabled ? 0.5 : 1,
        pointerEvents: disabled ? 'none' : 'auto',
      }}
    >
      {/* 헤더 */}
      <Typography sx={{ 
        p: 1.5, 
        borderBottom: `1px solid ${theme.palette.divider}`,
        fontSize: '14px',
        fontWeight: 600,
        bgcolor: theme.palette.mode === 'dark' ? theme.palette.grey[900] : theme.palette.grey[50],
      }}>
        🎨 전략 구성 요소
      </Typography>

      {/* 탭 */}
      <Tabs
        value={currentTab}
        onChange={(_, newValue) => setCurrentTab(newValue)}
        sx={{ 
          borderBottom: `1px solid ${theme.palette.divider}`,
          minHeight: '40px',
          '& .MuiTab-root': {
            minHeight: '40px',
            fontSize: '13px',
            fontWeight: 600,
          }
        }}
      >
        <Tab 
          value="manual" 
          label={
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <TouchAppIcon fontSize="small" />
              수동설정
            </Box>
          } 
        />
        <Tab 
          value="auto" 
          label={
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <AutoAwesomeIcon fontSize="small" />
              자동설정
            </Box>
          } 
        />
      </Tabs>

      {/* 탭 내용 */}
      <Box sx={{ flex: 1, overflow: 'auto' }}>
        {/* 수동설정 탭 */}
        {currentTab === 'manual' && (
          <Box sx={{ p: 1.5 }}>
            {/* 논리 연산자 섹션 */}
            <Box sx={{ mb: 2 }}>
              <Typography variant="subtitle2" fontWeight="bold" fontSize="13px" sx={{ mb: 1 }}>
                🔗 논리 연산자
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {operators.map((op) => (
                  <DraggableItem key={op.id} item={op} />
                ))}
              </Box>
            </Box>

            {/* 이동평균 섹션 */}
            <Box sx={{ mb: 2 }}>
              <Typography variant="subtitle2" fontWeight="bold" fontSize="13px" sx={{ mb: 1 }}>
                📈 이동평균 & 밴드
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {movingAverages.map((indicator) => (
                  <DraggableItem key={indicator.id} item={indicator} />
                ))}
              </Box>
            </Box>

            {/* 보조 지표 섹션 */}
            <Box>
              <Typography variant="subtitle2" fontWeight="bold" fontSize="13px" sx={{ mb: 1 }}>
                📊 보조 지표 (16가지)
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                {indicators.map((indicator) => (
                  <DraggableItem key={indicator.id} item={indicator} />
                ))}
              </Box>
            </Box>
          </Box>
        )}

        {/* 자동설정 탭 */}
        {currentTab === 'auto' && (
          <Box>
            <Box sx={{ p: 1.5, bgcolor: theme.palette.info.main, color: theme.palette.info.contrastText }}>
              <Typography variant="caption" sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                <AutoAwesomeIcon fontSize="small" />
                전략 템플릿을 선택하면 자동으로 조건이 추가됩니다
              </Typography>
            </Box>

            {allCategories.map((category) => {
              const buyTemplates = category.templates.filter(t => t.signal === 'buy');
              const sellTemplates = category.templates.filter(t => t.signal === 'sell');

              return (
                <Accordion 
                  key={category.id}
                  sx={{
                    '&:before': { display: 'none' },
                    boxShadow: 'none',
                    borderBottom: `1px solid ${theme.palette.divider}`,
                  }}
                >
                  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                    <Typography sx={{ fontWeight: 600, fontSize: '13px' }}>
                      {category.icon} {category.label}
                      <Chip 
                        label={`${category.templates.length}개`} 
                        size="small" 
                        sx={{ ml: 1, height: '18px', fontSize: '11px' }}
                      />
                    </Typography>
                  </AccordionSummary>
                  <AccordionDetails sx={{ p: 0 }}>
                    {/* 매수 전략 */}
                    {buyTemplates.length > 0 && (
                      <Box>
                        <Box sx={{ 
                          px: 2, 
                          py: 0.5, 
                          bgcolor: theme.palette.success.main + '20',
                          display: 'flex',
                          alignItems: 'center',
                          gap: 0.5,
                        }}>
                          <TrendingUpIcon fontSize="small" sx={{ color: theme.palette.success.main }} />
                          <Typography variant="caption" sx={{ fontWeight: 600, color: theme.palette.success.main }}>
                            매수 전략 ({buyTemplates.length}개)
                          </Typography>
                        </Box>
                        <List dense disablePadding>
                          {buyTemplates.map((template) => (
                            <ListItem key={template.id} disablePadding>
                              <ListItemButton
                                onClick={() => onTemplateSelect?.(template)}
                                sx={{
                                  py: 1,
                                  px: 2,
                                  '&:hover': {
                                    bgcolor: theme.palette.success.main + '10',
                                  },
                                }}
                              >
                                <ListItemText
                                  primary={getDynamicTemplateName(template, maSettings)}
                                  secondary={getDynamicTemplateDescription(template, maSettings)}
                                  primaryTypographyProps={{
                                    fontSize: '12px',
                                    fontWeight: 600,
                                  }}
                                  secondaryTypographyProps={{
                                    fontSize: '11px',
                                  }}
                                />
                              </ListItemButton>
                            </ListItem>
                          ))}
                        </List>
                      </Box>
                    )}

                    {/* 매도 전략 */}
                    {sellTemplates.length > 0 && (
                      <Box>
                        <Box sx={{ 
                          px: 2, 
                          py: 0.5, 
                          bgcolor: theme.palette.error.main + '20',
                          display: 'flex',
                          alignItems: 'center',
                          gap: 0.5,
                        }}>
                          <TrendingDownIcon fontSize="small" sx={{ color: theme.palette.error.main }} />
                          <Typography variant="caption" sx={{ fontWeight: 600, color: theme.palette.error.main }}>
                            매도 전략 ({sellTemplates.length}개)
                          </Typography>
                        </Box>
                        <List dense disablePadding>
                          {sellTemplates.map((template) => (
                            <ListItem key={template.id} disablePadding>
                              <ListItemButton
                                onClick={() => onTemplateSelect?.(template)}
                                sx={{
                                  py: 1,
                                  px: 2,
                                  '&:hover': {
                                    bgcolor: theme.palette.error.main + '10',
                                  },
                                }}
                              >
                                <ListItemText
                                  primary={getDynamicTemplateName(template, maSettings)}
                                  secondary={getDynamicTemplateDescription(template, maSettings)}
                                  primaryTypographyProps={{
                                    fontSize: '12px',
                                    fontWeight: 600,
                                  }}
                                  secondaryTypographyProps={{
                                    fontSize: '11px',
                                  }}
                                />
                              </ListItemButton>
                            </ListItem>
                          ))}
                        </List>
                      </Box>
                    )}
                  </AccordionDetails>
                </Accordion>
              );
            })}
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default NodePalette;
