import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Typography,
  Button,
  Card,
  CardContent,
  CardActions,
  Grid,
  Switch,
  FormControlLabel,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Alert,
  CircularProgress,
  Divider,
  IconButton,
  Tooltip,
  Tabs,
  Tab,
  Paper,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  ListItemButton,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Checkbox,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import TrendingDownIcon from '@mui/icons-material/TrendingDown';
import TrendingFlatIcon from '@mui/icons-material/TrendingFlat';
import ViewModuleIcon from '@mui/icons-material/ViewModule';
import AllInclusiveIcon from '@mui/icons-material/AllInclusive';
import RefreshIcon from '@mui/icons-material/Refresh';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import LibraryAddIcon from '@mui/icons-material/LibraryAdd';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import WarningIcon from '@mui/icons-material/Warning';
import VerifiedIcon from '@mui/icons-material/Verified';
import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import FileUploadIcon from '@mui/icons-material/FileUpload';
import DeleteSweepIcon from '@mui/icons-material/DeleteSweep';

import {
  StrategyRuleDto,
  TrendType,
  SignalType,
  ConditionGroupDto,
  StrategyConditionDto,
  IndicatorType,
  ConditionType,
  LogicalOperator,
  getStrategyRules,
  getStrategyRule,
  createStrategyRule,
  updateStrategyRule,
  deleteStrategyRule,
  toggleStrategyRule,
  getTrendDisplayName,
  getIndicatorDisplayName,
  getConditionDisplayName,
  createEmptyRule,
  createEmptyGroup,
  createEmptyCondition,
} from '../../services/strategyRuleApi';

import {
  getCachedPeriodsMap,
  isPeriodRequired,
  invalidatePeriodsCache,
} from '../../services/indicatorPeriodApi';

// 추세 타입 옵션
const TREND_TYPES: { value: TrendType; label: string; icon: React.ReactNode; color: string }[] = [
  { value: 'ALL', label: '전체', icon: <AllInclusiveIcon />, color: '#9c27b0' },
  { value: 'UPTREND', label: '상승추세 (정배열)', icon: <TrendingUpIcon />, color: '#4caf50' },
  { value: 'DOWNTREND', label: '하락추세 (역배열)', icon: <TrendingDownIcon />, color: '#f44336' },
  { value: 'SIDEWAYS', label: '횡보', icon: <TrendingFlatIcon />, color: '#ff9800' },
  { value: 'RANGE', label: '박스권', icon: <ViewModuleIcon />, color: '#2196f3' },
];

// 지표 타입 옵션 (업비트 16개 보조지표)
const INDICATOR_OPTIONS: { value: IndicatorType; label: string }[] = [
  { value: 'VOLUME', label: '거래량' },
  { value: 'MACD', label: 'MACD' },
  { value: 'STOCHASTIC', label: 'Stochastic Slow' },
  { value: 'RSI', label: 'RSI' },
  { value: 'ADX', label: 'ADX' },
  { value: 'CCI', label: 'CCI' },
  { value: 'TRIX', label: 'TRIX' },
  { value: 'DISPARITY', label: '이격도' },
  { value: 'NEW_PSYCHOLOGICAL', label: '신심리도' },
  { value: 'INVEST_PSYCHOLOGICAL', label: '투자심리도' },
  { value: 'WILLIAMS_R', label: 'Williams %R' },
  { value: 'BWI', label: '볼린저밴드 %B' },
  { value: 'OBV', label: 'OBV' },
  { value: 'VOLUME_OSC', label: 'VolumeOSC' },
  { value: 'VR', label: 'VR' },
  { value: 'DMI', label: 'DMI' },
];

// 조건 타입 옵션
const CONDITION_OPTIONS: { value: ConditionType; label: string }[] = [
  { value: 'CROSS_UP', label: '상향 돌파' },
  { value: 'CROSS_DOWN', label: '하향 돌파' },
  { value: 'GOLDEN_CROSS', label: '골든 크로스' },
  { value: 'DEAD_CROSS', label: '데드 크로스' },
  { value: 'ABOVE', label: '이상' },
  { value: 'BELOW', label: '이하' },
  { value: 'ABOVE_STRICT', label: '초과' },
  { value: 'BELOW_STRICT', label: '미만' },
  { value: 'BETWEEN', label: '범위' },
  { value: 'OUTSIDE', label: '범위 외' },
  { value: 'INCREASING', label: '상승 중' },
  { value: 'DECREASING', label: '하락 중' },
  { value: 'TURNING_UP', label: '상승 전환' },
  { value: 'TURNING_DOWN', label: '하락 전환' },
  { value: 'OVERBOUGHT', label: '과매수' },
  { value: 'OVERSOLD', label: '과매도' },
  { value: 'ZERO_CROSS_UP', label: '0선 상향' },
  { value: 'ZERO_CROSS_DOWN', label: '0선 하향' },
];

// ==================== 조건 검증 로직 ====================

// 지표별 지원 기간 정의 (업비트 표준 16개)
const SUPPORTED_PERIODS: Record<IndicatorType, number[] | null> = {
  VOLUME: null, // 기간 불필요
  MACD: null, // 기간 불필요
  STOCHASTIC: [9, 14, 21],
  RSI: [7, 9, 14, 21, 28],
  ADX: [9, 14, 21],
  CCI: [13, 20, 26],
  TRIX: [9, 12, 15],
  DISPARITY: [5, 10, 20, 60, 120],
  NEW_PSYCHOLOGICAL: [10, 12, 20],
  INVEST_PSYCHOLOGICAL: [10, 12, 20],
  WILLIAMS_R: [9, 14, 21],
  BWI: [20],
  OBV: null, // 기간 불필요
  VOLUME_OSC: [5, 10, 20],
  VR: [10, 20, 26],
  DMI: [9, 14, 21],
};

// 값이 필요한 조건 타입
const VALUE_REQUIRED_CONDITIONS: ConditionType[] = [
  'CROSS_UP', 'CROSS_DOWN', 'ABOVE', 'BELOW', 'OVERBOUGHT', 'OVERSOLD'
];

// 범위 값이 필요한 조건 타입
const RANGE_VALUE_CONDITIONS: ConditionType[] = ['BETWEEN'];

// 기간이 필요한 지표 타입 (업비트 16개 기준)
const PERIOD_REQUIRED_INDICATORS: IndicatorType[] = [
  'STOCHASTIC', 'RSI', 'ADX', 'CCI', 'TRIX', 'DISPARITY',
  'NEW_PSYCHOLOGICAL', 'INVEST_PSYCHOLOGICAL', 'WILLIAMS_R',
  'BWI', 'VOLUME_OSC', 'VR', 'DMI'
];

// 검증 결과 타입
interface ValidationResult {
  isValid: boolean;
  errors: ValidationError[];
  warnings: ValidationWarning[];
}

interface ValidationError {
  type: 'error';
  groupIndex: number;
  conditionIndex?: number;
  message: string;
  code: string;
}

interface ValidationWarning {
  type: 'warning';
  groupIndex: number;
  conditionIndex?: number;
  message: string;
  code: string;
}

// signalType에 따라 조건 그룹 가져오기
const getConditionGroups = (rule: StrategyRuleDto): ConditionGroupDto[] => {
  // buyConditionGroups와 sellConditionGroups 합쳐서 반환
  const buyGroups = rule.buyConditionGroups || [];
  const sellGroups = rule.sellConditionGroups || [];
  return [...buyGroups, ...sellGroups];
};

// signalType에 따라 조건 그룹 설정하기
const setConditionGroups = (rule: StrategyRuleDto, groups: ConditionGroupDto[]): StrategyRuleDto => {
  // signalType에 따라 적절한 필드에 설정
  if (rule.signalType === 'BUY') {
    return { ...rule, buyConditionGroups: groups.map(g => ({ ...g, groupType: 'BUY' as const })) };
  } else {
    return { ...rule, sellConditionGroups: groups.map(g => ({ ...g, groupType: 'SELL' as const })) };
  }
};

// 현재 signalType에 해당하는 조건 그룹만 가져오기
const getCurrentConditionGroups = (rule: StrategyRuleDto): ConditionGroupDto[] => {
  if (rule.signalType === 'BUY') {
    return rule.buyConditionGroups || [];
  } else {
    return rule.sellConditionGroups || [];
  }
};

// 전략 규칙 검증 함수 (periodsMap: DB에서 가져온 동적 기간 맵)
const validateStrategyRule = (
  rule: StrategyRuleDto, 
  periodsMap?: Record<string, number[]>
): ValidationResult => {
  const errors: ValidationError[] = [];
  const warnings: ValidationWarning[] = [];
  
  // periodsMap이 있으면 동적 기간 사용, 없으면 기본값 사용
  const getSupportedPeriods = (indicatorType: IndicatorType): number[] | null => {
    if (periodsMap && periodsMap[indicatorType]) {
      return periodsMap[indicatorType];
    }
    return SUPPORTED_PERIODS[indicatorType];
  };

  // signalType에 해당하는 조건 그룹 가져오기
  const conditionGroups = getCurrentConditionGroups(rule);

  // 1. 기본 정보 검증
  if (!rule.name || rule.name.trim() === '') {
    errors.push({
      type: 'error',
      groupIndex: -1,
      message: '전략 이름이 비어있습니다.',
      code: 'EMPTY_NAME'
    });
  }

  // 2. 조건 그룹 존재 검증
  if (conditionGroups.length === 0) {
    errors.push({
      type: 'error',
      groupIndex: -1,
      message: '최소 1개의 조건 그룹이 필요합니다.',
      code: 'NO_GROUPS'
    });
    return { isValid: false, errors, warnings };
  }

  // 3. 각 조건 그룹 검증
  conditionGroups.forEach((group, groupIndex) => {
    // 그룹 내 조건 존재 여부
    if (!group.conditions || group.conditions.length === 0) {
      errors.push({
        type: 'error',
        groupIndex,
        message: `그룹 ${groupIndex + 1}: 최소 1개의 조건이 필요합니다.`,
        code: 'EMPTY_GROUP'
      });
      return;
    }

    // 활성화된 조건만 검증
    const enabledConditions = group.conditions.filter(c => c.enabled !== false);
    if (enabledConditions.length === 0) {
      warnings.push({
        type: 'warning',
        groupIndex,
        message: `그룹 ${groupIndex + 1}: 활성화된 조건이 없습니다.`,
        code: 'NO_ENABLED_CONDITIONS'
      });
    }

    // 각 조건 검증
    group.conditions.forEach((condition, condIndex) => {
      if (condition.enabled === false) return; // 비활성화된 조건은 스킵

      // 지표 타입 검증
      if (!condition.indicatorType) {
        errors.push({
          type: 'error',
          groupIndex,
          conditionIndex: condIndex,
          message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: 지표가 선택되지 않았습니다.`,
          code: 'NO_INDICATOR'
        });
      }

      // 조건 타입 검증
      if (!condition.conditionType) {
        errors.push({
          type: 'error',
          groupIndex,
          conditionIndex: condIndex,
          message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: 조건이 선택되지 않았습니다.`,
          code: 'NO_CONDITION_TYPE'
        });
      }

      // 기간 검증 (기간이 필요한 지표)
      if (condition.indicatorType && PERIOD_REQUIRED_INDICATORS.includes(condition.indicatorType)) {
        const supportedPeriods = getSupportedPeriods(condition.indicatorType);
        
        if (!condition.period) {
          errors.push({
            type: 'error',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: ${getIndicatorDisplayName(condition.indicatorType)}에 기간이 필요합니다.`,
            code: 'PERIOD_REQUIRED'
          });
        } else if (supportedPeriods && !supportedPeriods.includes(condition.period)) {
          errors.push({
            type: 'error',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: ${getIndicatorDisplayName(condition.indicatorType)}의 기간 ${condition.period}은(는) 지원되지 않습니다. 지원 기간: ${supportedPeriods.join(', ')}`,
            code: 'UNSUPPORTED_PERIOD'
          });
        }
      }

      // 목표값 검증 (값이 필요한 조건)
      if (condition.conditionType && VALUE_REQUIRED_CONDITIONS.includes(condition.conditionType)) {
        if (condition.targetValue === undefined || condition.targetValue === null) {
          errors.push({
            type: 'error',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: ${getConditionDisplayName(condition.conditionType)} 조건에 기준값이 필요합니다.`,
            code: 'VALUE_REQUIRED'
          });
        }
      }

      // 범위 값 검증 (BETWEEN, OUTSIDE)
      if (condition.conditionType && RANGE_VALUE_CONDITIONS.includes(condition.conditionType)) {
        if (condition.targetValue === undefined || condition.targetValue === null) {
          errors.push({
            type: 'error',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: 범위 시작값이 필요합니다.`,
            code: 'RANGE_START_REQUIRED'
          });
        }
        if (condition.secondaryValue === undefined || condition.secondaryValue === null) {
          errors.push({
            type: 'error',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: 범위 끝값이 필요합니다.`,
            code: 'RANGE_END_REQUIRED'
          });
        }
        if (condition.targetValue !== undefined && condition.secondaryValue !== undefined &&
            condition.targetValue >= condition.secondaryValue) {
          errors.push({
            type: 'error',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: 범위 시작값(${condition.targetValue})이 끝값(${condition.secondaryValue})보다 작아야 합니다.`,
            code: 'INVALID_RANGE'
          });
        }
      }

      // RSI/Stochastic 값 범위 검증 (업비트 16개)
      if (condition.indicatorType && ['RSI', 'STOCHASTIC'].includes(condition.indicatorType)) {
        if (condition.targetValue !== undefined && (condition.targetValue < 0 || condition.targetValue > 100)) {
          warnings.push({
            type: 'warning',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: ${getIndicatorDisplayName(condition.indicatorType)} 값은 일반적으로 0~100 범위입니다. 현재 값: ${condition.targetValue}`,
            code: 'UNUSUAL_VALUE_RANGE'
          });
        }
      }

      // 골든크로스/데드크로스 지표 호환성 검증 (업비트 16개)
      if (condition.conditionType === 'GOLDEN_CROSS' || condition.conditionType === 'DEAD_CROSS') {
        const crossCompatibleIndicators: IndicatorType[] = ['MACD', 'STOCHASTIC', 'DMI', 'TRIX'];
        if (condition.indicatorType && !crossCompatibleIndicators.includes(condition.indicatorType)) {
          warnings.push({
            type: 'warning',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: ${getIndicatorDisplayName(condition.indicatorType)}은(는) ${getConditionDisplayName(condition.conditionType)} 조건과 호환성이 낮을 수 있습니다. 권장 지표: MACD, Stochastic, DMI, TRIX`,
            code: 'CROSS_COMPATIBILITY'
          });
        }
      }

      // 다이버전스 조건 지표 호환성 (업비트 16개)
      if (condition.conditionType === 'DIVERGENCE_BULLISH' || condition.conditionType === 'DIVERGENCE_BEARISH') {
        const divergenceCompatibleIndicators: IndicatorType[] = ['RSI', 'MACD', 'CCI', 'STOCHASTIC'];
        if (condition.indicatorType && !divergenceCompatibleIndicators.includes(condition.indicatorType)) {
          warnings.push({
            type: 'warning',
            groupIndex,
            conditionIndex: condIndex,
            message: `그룹 ${groupIndex + 1}, 조건 ${condIndex + 1}: 다이버전스 분석은 RSI, MACD, CCI, Stochastic과 주로 사용됩니다.`,
            code: 'DIVERGENCE_COMPATIBILITY'
          });
        }
      }
    });
  });

  // 4. 논리적 일관성 검증
  // 같은 지표에 대해 상반된 조건 체크 (예: RSI > 70 AND RSI < 30)
  conditionGroups.forEach((group, groupIndex) => {
    if (group.logicalOperator === 'AND') {
      const enabledConditions = group.conditions.filter(c => c.enabled !== false);
      
      // 같은 지표에 대한 조건들 그룹화
      const conditionsByIndicator = new Map<string, StrategyConditionDto[]>();
      enabledConditions.forEach(cond => {
        const key = `${cond.indicatorType}_${cond.period || 'default'}`;
        if (!conditionsByIndicator.has(key)) {
          conditionsByIndicator.set(key, []);
        }
        conditionsByIndicator.get(key)!.push(cond);
      });

      // 각 지표별로 상반된 조건 체크
      conditionsByIndicator.forEach((conditions, key) => {
        if (conditions.length >= 2) {
          const hasAbove = conditions.some(c => ['ABOVE', 'ABOVE_STRICT', 'OVERBOUGHT'].includes(c.conditionType));
          const hasBelow = conditions.some(c => ['BELOW', 'BELOW_STRICT', 'OVERSOLD'].includes(c.conditionType));
          
          if (hasAbove && hasBelow) {
            const aboveCond = conditions.find(c => ['ABOVE', 'ABOVE_STRICT', 'OVERBOUGHT'].includes(c.conditionType));
            const belowCond = conditions.find(c => ['BELOW', 'BELOW_STRICT', 'OVERSOLD'].includes(c.conditionType));
            
            if (aboveCond && belowCond && 
                aboveCond.targetValue !== undefined && belowCond.targetValue !== undefined &&
                aboveCond.targetValue >= belowCond.targetValue) {
              errors.push({
                type: 'error',
                groupIndex,
                message: `그룹 ${groupIndex + 1}: 동일 지표에 대해 상충하는 조건이 있습니다. (>= ${aboveCond.targetValue} AND <= ${belowCond.targetValue}는 불가능)`,
                code: 'CONFLICTING_CONDITIONS'
              });
            }
          }
        }
      });
    }
  });

  return {
    isValid: errors.length === 0,
    errors,
    warnings
  };
};

// 검증 결과 표시 컴포넌트
interface ValidationResultDisplayProps {
  result: ValidationResult | null;
  onClose: () => void;
}

const ValidationResultDisplay: React.FC<ValidationResultDisplayProps> = ({ result, onClose }) => {
  if (!result) return null;

  return (
    <Box sx={{ mt: 2 }}>
      <Alert 
        severity={result.isValid ? 'success' : 'error'}
        icon={result.isValid ? <VerifiedIcon /> : <ErrorIcon />}
        onClose={onClose}
        sx={{ mb: result.errors.length > 0 || result.warnings.length > 0 ? 2 : 0 }}
      >
        <Typography variant="subtitle2" fontWeight="bold">
          {result.isValid ? '✅ 검증 통과 (PASS)' : '❌ 검증 실패 (FAIL)'}
        </Typography>
        <Typography variant="body2">
          {result.isValid 
            ? '모든 조건이 정상적으로 설정되었습니다. 저장해도 됩니다.'
            : `${result.errors.length}개의 오류가 발견되었습니다. 수정 후 다시 검증해주세요.`}
        </Typography>
      </Alert>

      {result.errors.length > 0 && (
        <Paper variant="outlined" sx={{ p: 2, mb: 2, bgcolor: 'error.50' }}>
          <Typography variant="subtitle2" color="error" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <ErrorIcon fontSize="small" />
            오류 ({result.errors.length}개)
          </Typography>
          <List dense>
            {result.errors.map((error, idx) => (
              <ListItem key={idx} sx={{ py: 0.5, pl: 0 }}>
                <ListItemText 
                  primary={error.message}
                  primaryTypographyProps={{ 
                    variant: 'body2', 
                    color: 'error.main',
                    sx: { fontFamily: 'monospace' }
                  }}
                />
              </ListItem>
            ))}
          </List>
        </Paper>
      )}

      {result.warnings.length > 0 && (
        <Paper variant="outlined" sx={{ p: 2, bgcolor: 'warning.50' }}>
          <Typography variant="subtitle2" color="warning.dark" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <WarningIcon fontSize="small" />
            경고 ({result.warnings.length}개)
          </Typography>
          <List dense>
            {result.warnings.map((warning, idx) => (
              <ListItem key={idx} sx={{ py: 0.5, pl: 0 }}>
                <ListItemText 
                  primary={warning.message}
                  primaryTypographyProps={{ 
                    variant: 'body2', 
                    color: 'warning.dark' 
                  }}
                />
              </ListItem>
            ))}
          </List>
        </Paper>
      )}
    </Box>
  );
};

// 조건 설명 자동 생성
const generateConditionDescription = (condition: StrategyConditionDto, signalType: SignalType): string => {
  const indicator = getIndicatorDisplayName(condition.indicatorType);
  const conditionName = getConditionDisplayName(condition.conditionType);
  const signalLabel = signalType === 'BUY' ? '매수' : '매도';

  let desc = indicator;
  if (condition.period) {
    desc += `(${condition.period})`;
  }
  desc += ` ${conditionName}`;
  
  if (condition.targetValue !== undefined) {
    desc += ` ${condition.targetValue}`;
    if (condition.secondaryValue !== undefined && condition.conditionType === 'BETWEEN') {
      desc += ` ~ ${condition.secondaryValue}`;
    }
  }
  
  desc += ` 시 ${signalLabel} 신호`;
  return desc;
};

// 규칙 설명 자동 생성 (조건이 완전히 선택된 경우에만 포함)
const generateRuleDescription = (rule: StrategyRuleDto): string => {
  const conditionGroups = getCurrentConditionGroups(rule);
  if (conditionGroups.length === 0) {
    return '';
  }

  const signalLabel = rule.signalType === 'BUY' ? '매수' : '매도';
  const trendLabel = TREND_TYPES.find(t => t.value === rule.trendType)?.label || '';
  const parts: string[] = [];

  conditionGroups.forEach((group) => {
    const conditionParts: string[] = [];
    
    // 활성화되고 완전히 설정된 조건만 포함
    group.conditions
      .filter((cond) => cond.enabled !== false && cond.indicatorType && cond.conditionType)
      .forEach((cond) => {
        let condDesc = getIndicatorDisplayName(cond.indicatorType);
        
        // 기간이 필요한 지표에 기간 표시 (업비트 16개)
        if (cond.period && !['VOLUME', 'MACD', 'OBV'].includes(cond.indicatorType)) {
          condDesc += `(${cond.period})`;
        }
        
        condDesc += ` ${getConditionDisplayName(cond.conditionType)}`;
        
        // 값이 필요한 조건에만 값 표시
        const valueNeededConditions = ['ABOVE', 'BELOW', 'ABOVE_STRICT', 'BELOW_STRICT', 'CROSS_UP', 'CROSS_DOWN', 'OVERBOUGHT', 'OVERSOLD'];
        if (valueNeededConditions.includes(cond.conditionType) && cond.targetValue !== undefined && cond.targetValue !== null) {
          condDesc += ` ${cond.targetValue}`;
        }
        
        // 범위 조건
        if (cond.conditionType === 'BETWEEN' && cond.targetValue !== undefined && cond.secondaryValue !== undefined) {
          condDesc += ` ${cond.targetValue} ~ ${cond.secondaryValue}`;
        }
        
        conditionParts.push(condDesc);
      });

    if (conditionParts.length > 0) {
      const groupDesc = conditionParts.join(` ${group.logicalOperator} `);
      parts.push(conditionParts.length > 1 ? `(${groupDesc})` : groupDesc);
    }
  });

  if (parts.length === 0) return '';
  
  // 추세 정보 포함
  let description = parts.join(' AND ');
  if (trendLabel && rule.trendType !== 'ALL') {
    description = `[${trendLabel}] ` + description;
  }
  description += ` → ${signalLabel}`;
  
  return description;
};

// 기존 전략 선택 다이얼로그
interface ExistingStrategyDialogProps {
  open: boolean;
  onClose: () => void;
  onSelectConditions: (conditions: ConditionGroupDto[]) => void;
  existingRules: StrategyRuleDto[];
}

const ExistingStrategyDialog: React.FC<ExistingStrategyDialogProps> = ({
  open, onClose, onSelectConditions, existingRules
}) => {
  const [selectedRuleId, setSelectedRuleId] = useState<number | null>(null);
  const [selectedRule, setSelectedRule] = useState<StrategyRuleDto | null>(null);
  const [selectedGroupIds, setSelectedGroupIds] = useState<Set<number>>(new Set());
  const [loading, setLoading] = useState(false);

  // 규칙 선택 시 상세 조회
  const handleRuleSelect = async (ruleId: number) => {
    setSelectedRuleId(ruleId);
    setSelectedGroupIds(new Set());
      setLoading(true);
    try {
      const ruleDetail = await getStrategyRule(ruleId);
      setSelectedRule(ruleDetail);
      // 기본적으로 모든 그룹 선택
      const allGroups = getConditionGroups(ruleDetail);
      const allGroupIds = new Set(allGroups.map((g, idx) => idx));
      setSelectedGroupIds(allGroupIds);
    } catch (error) {
      console.error('전략 상세 조회 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  // 그룹 선택 토글
  const toggleGroupSelection = (groupIndex: number) => {
    const newSelected = new Set(selectedGroupIds);
    if (newSelected.has(groupIndex)) {
      newSelected.delete(groupIndex);
    } else {
      newSelected.add(groupIndex);
    }
    setSelectedGroupIds(newSelected);
  };

  // 선택된 조건 그룹 추가
  const handleAddConditions = () => {
    if (!selectedRule) {
      console.error('선택된 규칙이 없습니다.');
      return;
    }
    
    const allGroups = getConditionGroups(selectedRule);
    if (allGroups.length === 0) {
      console.error('조건 그룹이 없습니다.');
      return;
    }
    
    console.log('선택된 규칙:', selectedRule);
    console.log('선택된 그룹 인덱스:', Array.from(selectedGroupIds));
    
    const selectedGroups: ConditionGroupDto[] = allGroups
      .filter((_, idx) => selectedGroupIds.has(idx))
      .map((group) => {
        // 조건들 깊은 복사
        const copiedConditions: StrategyConditionDto[] = (group.conditions || []).map((c) => ({
          indicatorType: c.indicatorType,
          conditionType: c.conditionType,
          targetValue: c.targetValue,
          secondaryValue: c.secondaryValue,
          period: c.period,
          enabled: c.enabled ?? true,
          orderIndex: c.orderIndex ?? 0,
          description: c.description,
        }));
        
        return {
          logicalOperator: group.logicalOperator,
          orderIndex: group.orderIndex ?? 0,
          name: group.name,
          conditions: copiedConditions,
          childGroups: [],
        };
      });
    
    console.log('복사된 그룹:', selectedGroups);
    
    if (selectedGroups.length === 0) {
      console.error('선택된 그룹이 없습니다.');
      return;
    }
    
    onSelectConditions(selectedGroups);
    onClose();
    setSelectedRuleId(null);
    setSelectedRule(null);
    setSelectedGroupIds(new Set());
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <LibraryAddIcon color="primary" />
          기존 전략에서 조건 가져오기
        </Box>
      </DialogTitle>
      <DialogContent>
        <Grid container spacing={2} sx={{ mt: 1 }}>
          {/* 왼쪽: 전략 목록 */}
          <Grid item xs={12} md={5}>
            <Typography variant="subtitle2" gutterBottom fontWeight="bold">
              전략 선택
                  </Typography>
            <Paper variant="outlined" sx={{ maxHeight: 400, overflow: 'auto' }}>
              <List dense>
                {existingRules.map((rule) => (
                  <ListItemButton
                    key={rule.id}
                    selected={selectedRuleId === rule.id}
                    onClick={() => handleRuleSelect(rule.id!)}
                  >
                    <ListItemText
                      primary={
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Chip
                            label={rule.signalType === 'BUY' ? '매수' : '매도'}
                    size="small"
                            color={rule.signalType === 'BUY' ? 'success' : 'error'}
                            sx={{ height: 20 }}
                  />
                          <Typography variant="body2">{rule.name}</Typography>
                </Box>
                      }
                      secondary={`${rule.totalConditionCount || 0}개 조건`}
                    />
                    {selectedRuleId === rule.id && (
                      <CheckCircleIcon color="primary" fontSize="small" />
                    )}
                  </ListItemButton>
                ))}
                {existingRules.length === 0 && (
                  <ListItem>
                    <ListItemText secondary="저장된 전략이 없습니다" />
                  </ListItem>
                )}
              </List>
            </Paper>
                      </Grid>

          {/* 오른쪽: 조건 그룹 선택 */}
          <Grid item xs={12} md={7}>
            <Typography variant="subtitle2" gutterBottom fontWeight="bold">
              가져올 조건 그룹 선택
                          </Typography>
            <Paper variant="outlined" sx={{ maxHeight: 400, overflow: 'auto', p: 1 }}>
              {loading ? (
                <Box display="flex" justifyContent="center" p={3}>
                  <CircularProgress size={24} />
                </Box>
              ) : selectedRule ? (
                getConditionGroups(selectedRule).length > 0 ? (
                  getConditionGroups(selectedRule).map((group, groupIndex) => (
                    <Accordion key={groupIndex} defaultExpanded>
                      <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
                          <Checkbox
                            checked={selectedGroupIds.has(groupIndex)}
                            onChange={() => toggleGroupSelection(groupIndex)}
                            onClick={(e) => e.stopPropagation()}
                            size="small"
                          />
                          <Typography variant="body2" fontWeight="bold">
                            그룹 {groupIndex + 1}
                          </Typography>
                          <Chip 
                            label={group.logicalOperator} 
                            size="small" 
                            variant="outlined"
                            sx={{ height: 20 }}
                          />
                          <Chip 
                            label={`${group.conditions.length}개 조건`}
                            size="small"
                            color="primary"
                            sx={{ height: 20 }}
                          />
                        </Box>
                      </AccordionSummary>
                      <AccordionDetails sx={{ bgcolor: 'action.hover' }}>
                        {group.conditions.map((condition, condIndex) => (
                          <Box 
                            key={condIndex} 
                            sx={{ 
                              p: 1, 
                              mb: 1, 
                              bgcolor: 'background.paper',
                              borderRadius: 1,
                              border: '1px solid',
                              borderColor: 'divider'
                            }}
                          >
                            <Typography variant="body2">
                              <strong>{getIndicatorDisplayName(condition.indicatorType)}</strong>
                              {condition.period && ` (${condition.period})`}
                              {' '}
                              <Chip 
                                label={getConditionDisplayName(condition.conditionType)}
                                size="small"
                                sx={{ height: 18 }}
                              />
                              {condition.targetValue !== undefined && ` ${condition.targetValue}`}
                          </Typography>
                            {condition.description && (
                      <Typography variant="caption" color="text.secondary">
                                {condition.description}
                      </Typography>
                            )}
                          </Box>
                        ))}
                      </AccordionDetails>
                    </Accordion>
                  ))
                ) : (
                  <Typography variant="body2" color="text.secondary" sx={{ p: 2 }}>
                    이 전략에는 조건이 없습니다.
                      </Typography>
                )
              ) : (
                <Typography variant="body2" color="text.secondary" sx={{ p: 2, textAlign: 'center' }}>
                  왼쪽에서 전략을 선택하세요
                      </Typography>
                  )}
            </Paper>
                </Grid>
      </Grid>

        {selectedRule && selectedGroupIds.size > 0 && (
        <Alert severity="info" sx={{ mt: 2 }}>
            <strong>{selectedRule.name}</strong>에서 {selectedGroupIds.size}개의 조건 그룹을 가져옵니다.
        </Alert>
      )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>취소</Button>
        <Button 
          variant="contained"
          onClick={handleAddConditions}
          disabled={!selectedRule || selectedGroupIds.size === 0}
          startIcon={<ContentCopyIcon />}
        >
          선택한 조건 가져오기 ({selectedGroupIds.size}개)
        </Button>
      </DialogActions>
    </Dialog>
  );
};

interface RuleEditDialogProps {
  open: boolean;
  rule: StrategyRuleDto | null;
  isNew: boolean;
  existingRules: StrategyRuleDto[];
  onClose: () => void;
  onChange: (rule: StrategyRuleDto) => void;
  onSave: () => void;
}

const RuleEditDialog: React.FC<RuleEditDialogProps> = ({
  open, rule, isNew, existingRules, onClose, onChange, onSave
}) => {
  const [existingStrategyDialogOpen, setExistingStrategyDialogOpen] = useState(false);
  const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
  const [isValidating, setIsValidating] = useState(false);
  const [periodsMap, setPeriodsMap] = useState<Record<string, number[]>>({});
  const [showValidationRequired, setShowValidationRequired] = useState(false);
  const [periodsLoading, setPeriodsLoading] = useState(false);

  // 지표별 기간 맵 로드 (다이얼로그 열릴 때마다 새로 로드)
  useEffect(() => {
    if (open) {
      setPeriodsLoading(true);
      // 캐시 무효화 후 새로 로드
      invalidatePeriodsCache();
      getCachedPeriodsMap()
        .then((data) => {
          console.log('기간 맵 로드 완료:', data);
          setPeriodsMap(data);
        })
        .catch((error) => {
          console.error('기간 맵 로드 실패:', error);
          setPeriodsMap({});
        })
        .finally(() => {
          setPeriodsLoading(false);
        });
    }
  }, [open]);

  // 검증 실행
  const handleValidate = useCallback(() => {
    if (!rule) return;
    
    setIsValidating(true);
    // 비동기처럼 보이게 하기 위한 짧은 지연
    setTimeout(() => {
      const result = validateStrategyRule(rule, periodsMap);
      setValidationResult(result);
      setIsValidating(false);
    }, 300);
  }, [rule, periodsMap]);

  // 다이얼로그 닫을 때 검증 결과 초기화
  const handleClose = useCallback(() => {
    setValidationResult(null);
    setShowValidationRequired(false);
    onClose();
  }, [onClose]);

  // 저장 시도 핸들러
  const handleSaveAttempt = useCallback(() => {
    if (!rule) return;
    
    // 검증이 아직 실행되지 않았거나 실패한 경우
    if (!validationResult) {
      setShowValidationRequired(true);
      // 자동으로 검증 실행
      const result = validateStrategyRule(rule, periodsMap);
      setValidationResult(result);
      return;
    }
    
    if (!validationResult.isValid) {
      setShowValidationRequired(true);
      return;
    }
    
    // 검증 통과 시 저장
    setShowValidationRequired(false);
    onSave();
  }, [rule, periodsMap, validationResult, onSave]);

  // 상태 업데이트 및 설명 자동 생성
  const updateRuleWithDescription = useCallback((updatedRule: StrategyRuleDto) => {
    const newDescription = generateRuleDescription(updatedRule);
    setValidationResult(null); // 변경 시 검증 결과 초기화
    setShowValidationRequired(false); // 변경 시 메시지 초기화
    onChange({ ...updatedRule, description: newDescription });
  }, [onChange]);

  // 기존 전략에서 조건 가져오기 - useCallback으로 메모이제이션
  const handleImportConditions = useCallback((importedGroups: ConditionGroupDto[]) => {
    if (!rule) return;
    
    console.log('가져온 조건 그룹:', importedGroups);
    
    const currentGroups = getCurrentConditionGroups(rule);
    
    // 가져온 그룹들의 인덱스 재조정 및 ID 제거
    const reindexedGroups: ConditionGroupDto[] = importedGroups.map((group, idx) => ({
      ...group,
      id: undefined,
      strategyRuleId: undefined,
      orderIndex: currentGroups.length + idx,
      groupType: rule.signalType === 'BUY' ? 'BUY' as const : 'SELL' as const,
      conditions: group.conditions.map((cond, condIdx) => ({
        ...cond,
        id: undefined,
        conditionGroupId: undefined,
        orderIndex: condIdx,
      })),
      childGroups: group.childGroups?.map((child, childIdx) => ({
        ...child,
        id: undefined,
        orderIndex: childIdx,
      })) || [],
    }));
    
    const newConditionGroups = [...currentGroups, ...reindexedGroups];
    
    console.log('업데이트된 조건 그룹:', newConditionGroups);
    
    const updatedRule = setConditionGroups(rule, newConditionGroups);
    
    // 설명 자동 생성
    updatedRule.description = generateRuleDescription(updatedRule);
    
    // 상태 직접 업데이트
    onChange(updatedRule);
  }, [rule, onChange]);

  if (!rule) return null;

  // 현재 signalType에 해당하는 조건 그룹
  const currentGroups = getCurrentConditionGroups(rule);

  const handleGroupChange = (index: number, group: ConditionGroupDto) => {
    const newGroups = [...currentGroups];
    newGroups[index] = { ...group, groupType: rule.signalType === 'BUY' ? 'BUY' as const : 'SELL' as const };
    const updatedRule = setConditionGroups(rule, newGroups);
    updateRuleWithDescription(updatedRule);
  };

  const addGroup = () => {
    const groupType = rule.signalType === 'BUY' ? 'BUY' as const : 'SELL' as const;
    const newGroup = { ...createEmptyGroup(currentGroups.length), groupType };
    const updatedRule = setConditionGroups(rule, [...currentGroups, newGroup]);
    updateRuleWithDescription(updatedRule);
  };

  const removeGroup = (index: number) => {
    if (currentGroups.length <= 1) return;
    const newGroups = currentGroups.filter((_, i) => i !== index);
    const updatedRule = setConditionGroups(rule, newGroups);
    updateRuleWithDescription(updatedRule);
  };

  const handleTrendTypeChange = (trendType: TrendType) => {
    updateRuleWithDescription({ ...rule, trendType });
  };

  const handleSignalTypeChange = (signalType: SignalType) => {
    updateRuleWithDescription({ ...rule, signalType });
  };

  return (
    <>
      <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
        <DialogTitle>
          {isNew ? '새 전략 규칙 생성' : '전략 규칙 수정'}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <Grid container spacing={2}>
              <Grid item xs={12}>
            <TextField
              fullWidth
                  label="규칙 이름"
                  value={rule.name}
                  onChange={(e) => onChange({ ...rule, name: e.target.value })}
              required
            />
              </Grid>

              <Grid item xs={12} md={6}>
                <FormControl fullWidth>
                  <InputLabel>신호 타입</InputLabel>
              <Select
                    value={rule.signalType}
                    label="신호 타입"
                    onChange={(e) => handleSignalTypeChange(e.target.value as SignalType)}
                  >
                    <MenuItem value="BUY">매수</MenuItem>
                    <MenuItem value="SELL">매도</MenuItem>
              </Select>
            </FormControl>
              </Grid>

              <Grid item xs={12} md={6}>
                <FormControl fullWidth>
                  <InputLabel>추세 타입</InputLabel>
                  <Select
                    value={rule.trendType || 'ALL'}
                    label="추세 타입"
                    onChange={(e) => handleTrendTypeChange(e.target.value as TrendType)}
                  >
                    {TREND_TYPES.map((trend) => (
                      <MenuItem key={trend.value} value={trend.value}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          {trend.icon}
                          {trend.label}
                        </Box>
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
            <TextField
              fullWidth
              label="설명"
                    value={rule.description || ''}
                    onChange={(e) => onChange({ ...rule, description: e.target.value })}
              multiline
              rows={2}
                    helperText="조건을 수정하면 자동으로 설명이 생성됩니다"
                  />
                  <Tooltip title="조건에서 설명 자동 생성">
                    <IconButton 
                      onClick={() => updateRuleWithDescription(rule)}
                      sx={{ mt: 1 }}
                    >
                      <RefreshIcon />
                    </IconButton>
                  </Tooltip>
                </Box>
              </Grid>

              <Grid item xs={12}>
            <FormControlLabel
              control={
                <Switch
                      checked={rule.enabled ?? true}
                      onChange={(e) => onChange({ ...rule, enabled: e.target.checked })}
                />
              }
                  label="활성화"
            />
              </Grid>
            </Grid>

                <Divider sx={{ my: 3 }} />

            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6">
                조건 그룹 ({currentGroups.length}개)
                    </Typography>
              <Box sx={{ display: 'flex', gap: 1 }}>
                <Button
                  variant="outlined"
                  size="small"
                  startIcon={<LibraryAddIcon />}
                  onClick={() => setExistingStrategyDialogOpen(true)}
                >
                  기존 전략에서 가져오기
                </Button>
                <Button
                  variant="contained"
                  size="small"
                  startIcon={<AddIcon />}
                  onClick={addGroup}
                >
                  새 그룹 추가
                </Button>
              </Box>
            </Box>

            {currentGroups.length === 0 && (
              <Alert severity="info" sx={{ mb: 2 }}>
                조건 그룹을 추가하거나 기존 전략에서 조건을 가져와 주세요.
                    </Alert>
            )}

            {periodsLoading && (
              <Alert severity="info" sx={{ mb: 2 }}>
                <CircularProgress size={16} sx={{ mr: 1 }} />
                지표별 기간 설정을 로드 중입니다...
              </Alert>
            )}

            {!periodsLoading && Object.keys(periodsMap).length === 0 && (
              <Alert severity="warning" sx={{ mb: 2 }}>
                지표별 기간 설정이 없습니다. 설정 → 보조지표에서 기간을 추가해주세요.
              </Alert>
            )}

            {currentGroups.map((group, groupIndex) => (
              <ConditionGroupEditor
                key={groupIndex}
                group={group}
                groupIndex={groupIndex}
                totalGroups={currentGroups.length}
                signalType={rule.signalType}
                periodsMap={periodsMap}
                periodsLoading={periodsLoading}
                onChange={(newGroup) => handleGroupChange(groupIndex, newGroup)}
                onRemove={() => removeGroup(groupIndex)}
              />
            ))}

            {/* 조건 검증 섹션 */}
            <Divider sx={{ my: 3 }} />
            
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <PlaylistAddCheckIcon />
                조건 검증
              </Typography>
              <Button
                variant="outlined"
                color={validationResult?.isValid ? 'success' : 'primary'}
                startIcon={isValidating ? <CircularProgress size={16} /> : <VerifiedIcon />}
                onClick={handleValidate}
                disabled={isValidating || currentGroups.length === 0}
              >
                {isValidating ? '검증 중...' : '조건 검토'}
              </Button>
            </Box>

            {showValidationRequired && !validationResult?.isValid ? (
              <Alert severity="warning" sx={{ mb: 2 }}>
                <Typography variant="body2">
                  <strong>⚠️ 조건 검증이 필요합니다!</strong>
                  <br />
                  전략 규칙을 저장하려면 먼저 <strong>조건 검토</strong> 버튼을 클릭하여 검증을 통과해야 합니다.
                  {validationResult && !validationResult.isValid && (
                    <>
                      <br /><br />
                      <strong>검증 실패 사유:</strong>
                      <br />
                      • 오류 {validationResult.errors.length}개{validationResult.warnings.length > 0 && `, 경고 ${validationResult.warnings.length}개`}가 발견되었습니다.
                      <br />
                      아래 검증 결과를 확인하고 오류를 수정해주세요.
                    </>
                  )}
                </Typography>
              </Alert>
            ) : (
              <Alert severity="info" sx={{ mb: 2 }}>
                <Typography variant="body2">
                  저장 전 <strong>조건 검토</strong> 버튼을 클릭하여 설정한 조건에 오류가 없는지 확인하세요.
                  <br />
                  • 검증을 통과해야만 전략 규칙을 저장할 수 있습니다.
                </Typography>
              </Alert>
            )}

            {/* 검증 결과 표시 */}
            <ValidationResultDisplay 
              result={validationResult} 
              onClose={() => setValidationResult(null)} 
            />
          </Box>
        </DialogContent>
        <DialogActions sx={{ px: 3, py: 2, gap: 1 }}>
          <Button onClick={handleClose}>취소</Button>
          <Button
            variant="outlined"
            color={validationResult?.isValid ? 'success' : 'info'}
            startIcon={validationResult?.isValid ? <CheckCircleIcon /> : <PlaylistAddCheckIcon />}
            onClick={handleValidate}
            disabled={isValidating || currentGroups.length === 0}
          >
            {isValidating ? '검증 중...' : validationResult?.isValid ? '✓ 검증 완료' : '조건 검토'}
          </Button>
          <Button 
            onClick={handleSaveAttempt} 
            variant="contained" 
            color={validationResult?.isValid ? 'success' : 'primary'}
            disabled={!rule.name || currentGroups.length === 0}
            startIcon={validationResult?.isValid ? <CheckCircleIcon /> : undefined}
          >
            {validationResult?.isValid ? '' : '🔒 '}{isNew ? '생성' : '저장'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 기존 전략 선택 다이얼로그 */}
      <ExistingStrategyDialog
        open={existingStrategyDialogOpen}
        onClose={() => setExistingStrategyDialogOpen(false)}
        onSelectConditions={handleImportConditions}
        existingRules={existingRules.filter(r => r.id !== rule.id)} // 현재 편집 중인 규칙 제외
                        />
                      </>
  );
};

interface ConditionGroupEditorProps {
  group: ConditionGroupDto;
  groupIndex: number;
  totalGroups: number;
  signalType: SignalType;
  periodsMap: Record<string, number[]>;
  periodsLoading?: boolean;
  onChange: (group: ConditionGroupDto) => void;
  onRemove: () => void;
}

const ConditionGroupEditor: React.FC<ConditionGroupEditorProps> = ({
  group, groupIndex, totalGroups, signalType, periodsMap, periodsLoading, onChange, onRemove
}) => {
  // 조건 변경 시 즉시 부모에 전파 (설명 갱신 트리거)
  const handleConditionChange = useCallback((index: number, condition: StrategyConditionDto) => {
    const newConditions = [...group.conditions];
    newConditions[index] = condition;
    console.log(`조건 ${index + 1} 변경:`, condition);
    onChange({ ...group, conditions: newConditions });
  }, [group, onChange]);

  // 새 조건 추가
  const addCondition = useCallback(() => {
    const newCondition = createEmptyCondition(group.conditions.length);
    console.log('새 조건 추가:', newCondition);
    onChange({
      ...group,
      conditions: [...group.conditions, newCondition],
    });
  }, [group, onChange]);

  // 조건 삭제
  const removeCondition = useCallback((index: number) => {
    if (group.conditions.length <= 1) return;
    const newConditions = group.conditions.filter((_, i) => i !== index);
    console.log(`조건 ${index + 1} 삭제, 남은 조건:`, newConditions.length);
    onChange({ ...group, conditions: newConditions });
  }, [group, onChange]);

  // 논리 연산자 변경
  const handleOperatorChange = useCallback((operator: LogicalOperator) => {
    console.log('논리 연산자 변경:', operator);
    onChange({ ...group, logicalOperator: operator });
  }, [group, onChange]);

  return (
    <Accordion defaultExpanded sx={{ mb: 2 }}>
      <AccordionSummary expandIcon={<ExpandMoreIcon />}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, width: '100%' }}>
          <Typography>그룹 {groupIndex + 1}</Typography>
          <FormControl size="small" sx={{ minWidth: 100 }}>
            <Select
              value={group.logicalOperator}
              onChange={(e) => {
                e.stopPropagation();
                handleOperatorChange(e.target.value as LogicalOperator);
              }}
              onClick={(e) => e.stopPropagation()}
            >
              <MenuItem value="AND">AND</MenuItem>
              <MenuItem value="OR">OR</MenuItem>
            </Select>
          </FormControl>
          <Chip 
            label={`${group.conditions.length}개 조건`} 
            size="small" 
                              color="primary"
            variant="outlined" 
          />
          <Box flexGrow={1} />
          {totalGroups > 1 && (
            <Tooltip title="그룹 삭제">
              <IconButton
                size="small"
                color="error"
                onClick={(e) => { e.stopPropagation(); onRemove(); }}
              >
                <DeleteIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          )}
        </Box>
      </AccordionSummary>
      <AccordionDetails>
        {group.conditions.map((condition, condIndex) => (
          <Box key={condIndex} sx={{ mb: 2, p: 2, bgcolor: 'background.default', borderRadius: 1 }}>
            <Grid container spacing={2} alignItems="center">
              <Grid item xs={12} sm={3}>
                    <FormControl fullWidth size="small">
                  <InputLabel>지표</InputLabel>
                      <Select
                    value={condition.indicatorType}
                    label="지표"
                    onChange={(e) => handleConditionChange(condIndex, { 
                      ...condition, 
                      indicatorType: e.target.value as IndicatorType 
                    })}
                  >
                    {INDICATOR_OPTIONS.map((opt) => (
                      <MenuItem key={opt.value} value={opt.value}>{opt.label}</MenuItem>
                    ))}
                      </Select>
                    </FormControl>
                </Grid>

              <Grid item xs={12} sm={3}>
                <FormControl fullWidth size="small">
                  <InputLabel>조건</InputLabel>
                  <Select
                    value={condition.conditionType}
                    label="조건"
                    onChange={(e) => handleConditionChange(condIndex, { 
                      ...condition, 
                      conditionType: e.target.value as ConditionType 
                    })}
                  >
                    {CONDITION_OPTIONS.map((opt) => (
                      <MenuItem key={opt.value} value={opt.value}>{opt.label}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
                      </Grid>

              <Grid item xs={6} sm={2}>
                <TextField
                  fullWidth
                  size="small"
                  label="기준값"
                  type="number"
                  value={condition.targetValue ?? ''}
                  onChange={(e) => handleConditionChange(condIndex, { 
                    ...condition, 
                    targetValue: e.target.value ? parseFloat(e.target.value) : undefined 
                  })}
                        />
                      </Grid>

              <Grid item xs={6} sm={2}>
                {isPeriodRequired(condition.indicatorType) ? (
                  (() => {
                    const availablePeriods = periodsMap[condition.indicatorType] || [];
                    const hasNoPeriods = availablePeriods.length === 0 && !periodsLoading;
                    
                    return (
                      <FormControl fullWidth size="small" error={hasNoPeriods}>
                        <InputLabel>기간</InputLabel>
                        <Select
                          value={condition.period ?? ''}
                          label="기간"
                          disabled={periodsLoading}
                          onChange={(e) => handleConditionChange(condIndex, { 
                            ...condition, 
                            period: e.target.value ? Number(e.target.value) : undefined 
                          })}
                        >
                          {periodsLoading ? (
                            <MenuItem value="" disabled>
                              로딩 중...
                            </MenuItem>
                          ) : hasNoPeriods ? (
                            <MenuItem value="" disabled>
                              기간 없음 - 설정에서 추가
                            </MenuItem>
                          ) : (
                            availablePeriods.map((period) => (
                              <MenuItem key={period} value={period}>{period}일</MenuItem>
                            ))
                          )}
                        </Select>
                        {hasNoPeriods && !periodsLoading && (
                          <Typography variant="caption" color="error" sx={{ mt: 0.5 }}>
                            설정 → 보조지표에서 기간 추가
                          </Typography>
                        )}
                      </FormControl>
                    );
                  })()
                ) : (
                  <TextField
                    fullWidth
                    size="small"
                    label="기간"
                    disabled
                    value="-"
                    helperText="필요없음"
                  />
                )}
              </Grid>

              <Grid item xs={12} sm={2}>
                <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                  <Tooltip title={condition.enabled ? '활성화됨' : '비활성화됨'}>
                        <Switch
                      checked={condition.enabled ?? true}
                      onChange={(e) => handleConditionChange(condIndex, { 
                        ...condition, 
                        enabled: e.target.checked 
                      })}
                      size="small"
                    />
                  </Tooltip>
                  {group.conditions.length > 1 && (
                    <Tooltip title="조건 삭제">
                      <IconButton
                        size="small"
                        color="error"
                        onClick={() => removeCondition(condIndex)}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  )}
                  </Box>
                      </Grid>
                      </Grid>

            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
              {generateConditionDescription(condition, signalType)}
                  </Typography>
          </Box>
        ))}

        <Button
          size="small"
          startIcon={<AddIcon />}
          onClick={addCondition}
        >
          조건 추가
        </Button>
      </AccordionDetails>
    </Accordion>
  );
};

const TradingStrategyTab: React.FC = () => {
  const [currentTrendTab, setCurrentTrendTab] = useState<TrendType>('ALL');
  const [rules, setRules] = useState<StrategyRuleDto[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // 다이얼로그 상태
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingRule, setEditingRule] = useState<StrategyRuleDto | null>(null);
  const [isNewRule, setIsNewRule] = useState(false);
  
  // Import 다이얼로그 상태
  const [importDialogOpen, setImportDialogOpen] = useState(false);
  const [importData, setImportData] = useState<StrategyRuleDto[] | null>(null);
  const [importLoading, setImportLoading] = useState(false);
  
  // 전체삭제 확인 다이얼로그
  const [deleteAllDialogOpen, setDeleteAllDialogOpen] = useState(false);
  const [deletingAll, setDeletingAll] = useState(false);

  // 규칙 목록 로드
  const loadRules = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getStrategyRules();
      setRules(data);
    } catch (err: any) {
      setError('전략 규칙을 불러오는데 실패했습니다: ' + (err.response?.data?.message || err.message));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadRules();
  }, [loadRules]);

  // 현재 탭에 맞는 규칙 필터링
  const filteredRules = rules.filter(rule => {
    if (currentTrendTab === 'ALL') {
      return rule.trendType === 'ALL' || !rule.trendType;
    }
    return rule.trendType === currentTrendTab;
  });

  // 매수/매도별 분류
  const buyRules = filteredRules.filter(r => r.signalType === 'BUY');
  const sellRules = filteredRules.filter(r => r.signalType === 'SELL');

  // 새 규칙 생성
  const handleNewRule = () => {
    setEditingRule(createEmptyRule('BUY', currentTrendTab));
    setIsNewRule(true);
    setDialogOpen(true);
  };

  // 규칙 수정
  const handleEditRule = async (rule: StrategyRuleDto) => {
    try {
      // 상세 정보 조회 (조건 그룹 포함)
      const ruleDetail = await getStrategyRule(rule.id!);
      setEditingRule({ ...ruleDetail });
      setIsNewRule(false);
      setDialogOpen(true);
    } catch (err: any) {
      setError('전략 상세 조회 실패: ' + (err.response?.data?.message || err.message));
    }
  };

  // 규칙 삭제
  const handleDeleteRule = async (id: number) => {
    if (!window.confirm('정말 이 규칙을 삭제하시겠습니까?')) return;
    
    try {
      await deleteStrategyRule(id);
      setSuccess('전략 규칙이 삭제되었습니다.');
      loadRules();
    } catch (err: any) {
      setError('삭제 실패: ' + (err.response?.data?.message || err.message));
    }
  };

  // 규칙 활성화/비활성화 토글
  const handleToggleRule = async (id: number, currentEnabled: boolean) => {
    const newEnabled = !currentEnabled;
    
    // 낙관적 업데이트
    setRules(prev => prev.map(r => 
      r.id === id ? { ...r, enabled: newEnabled } : r
    ));

    try {
      await toggleStrategyRule(id, newEnabled);
    } catch (err: any) {
      // 롤백
      setRules(prev => prev.map(r => 
        r.id === id ? { ...r, enabled: currentEnabled } : r
      ));
      setError('상태 변경 실패: ' + (err.response?.data?.message || err.message));
    }
  };

  // 규칙 저장
  const handleSaveRule = async () => {
    if (!editingRule) return;

    try {
      if (isNewRule) {
        await createStrategyRule(editingRule);
        setSuccess('새 전략 규칙이 생성되었습니다.');
      } else {
        await updateStrategyRule(editingRule.id!, editingRule);
        setSuccess('전략 규칙이 수정되었습니다.');
      }
      setDialogOpen(false);
      setEditingRule(null);
      loadRules();
    } catch (err: any) {
      setError('저장 실패: ' + (err.response?.data?.message || err.message));
    }
  };

  // 각 추세별 규칙 개수
  const getRuleCountByTrend = (trendType: TrendType) => {
    if (trendType === 'ALL') {
      return rules.filter(r => r.trendType === 'ALL' || !r.trendType).length;
    }
    return rules.filter(r => r.trendType === trendType).length;
  };

  // ==================== Export/Import 기능 ====================
  
  /**
   * 전략 목록을 JSON 파일로 내보내기
   */
  const handleExport = useCallback(async () => {
    try {
      if (rules.length === 0) {
        setError('내보낼 전략이 없습니다.');
        return;
      }

      // ID 및 시간 정보를 제외한 순수 전략 데이터만 추출
      const exportData = rules.map(rule => {
        const { id, createdAt, updatedAt, ...ruleData } = rule;
        
        // 조건 그룹에서도 ID 제거
        const cleanConditionGroups = (groups?: ConditionGroupDto[]) => {
          return groups?.map(group => {
            const { id: groupId, strategyRuleId, ...groupData } = group;
            return {
              ...groupData,
              conditions: group.conditions.map(cond => {
                const { id: condId, conditionGroupId, ...condData } = cond;
                return condData;
              })
            };
          });
        };

        return {
          ...ruleData,
          buyConditionGroups: cleanConditionGroups(rule.buyConditionGroups),
          sellConditionGroups: cleanConditionGroups(rule.sellConditionGroups),
        };
      });

      // JSON 파일로 다운로드
      const dataStr = JSON.stringify(exportData, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(dataBlob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = `trading-strategies-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      setSuccess(`${rules.length}개의 전략을 내보냈습니다.`);
    } catch (err: any) {
      setError('전략 내보내기 실패: ' + (err.message || '알 수 없는 오류'));
    }
  }, [rules]);

  /**
   * JSON 파일에서 전략 목록 불러오기
   */
  const handleImportFile = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string;
        const data = JSON.parse(content) as StrategyRuleDto[];
        
        // 데이터 유효성 검증
        if (!Array.isArray(data)) {
          setError('올바른 전략 파일 형식이 아닙니다.');
          return;
        }

        if (data.length === 0) {
          setError('파일에 전략 데이터가 없습니다.');
          return;
        }

        // 필수 필드 검증
        const isValid = data.every(rule => 
          rule.name && rule.signalType && 
          (rule.signalType === 'BUY' || rule.signalType === 'SELL')
        );

        if (!isValid) {
          setError('일부 전략의 필수 필드가 누락되었습니다.');
          return;
        }

        setImportData(data);
        setImportDialogOpen(true);
      } catch (err: any) {
        setError('파일 읽기 실패: ' + (err.message || '올바른 JSON 형식이 아닙니다.'));
      }
    };

    reader.onerror = () => {
      setError('파일을 읽을 수 없습니다.');
    };

    reader.readAsText(file);
    
    // 동일한 파일을 다시 선택할 수 있도록 값 초기화
    event.target.value = '';
  }, []);

  /**
   * Import된 전략들을 DB에 저장
   */
  const handleConfirmImport = useCallback(async () => {
    if (!importData) return;

    setImportLoading(true);
    let successCount = 0;
    let failCount = 0;
    const errors: string[] = [];

    try {
      // 기존 전략 이름 목록 가져오기
      const allRules = await getStrategyRules();
      const existingNames = new Set(allRules.map(r => r.name));

      for (const rule of importData) {
        try {
          // 이름 중복 체크 및 자동 변경
          let newName = rule.name;
          let counter = 1;
          while (existingNames.has(newName)) {
            newName = `${rule.name} (${counter})`;
            counter++;
          }

          // 새 이름을 목록에 추가 (다음 전략 체크용)
          existingNames.add(newName);

          // enabled가 undefined면 기본값 true로 설정
          const ruleToCreate = {
            ...rule,
            name: newName,
            enabled: rule.enabled ?? true,
          };
          
          await createStrategyRule(ruleToCreate);
          successCount++;

          if (newName !== rule.name) {
            console.log(`전략 이름 변경: "${rule.name}" → "${newName}"`);
          }
        } catch (err: any) {
          failCount++;
          const errorMsg = err.response?.data?.message || err.message || '알 수 없는 오류';
          errors.push(`"${rule.name}": ${errorMsg}`);
        }
      }

      // 결과 표시
      if (successCount > 0) {
        setSuccess(`${successCount}개의 전략을 성공적으로 가져왔습니다.`);
        loadRules(); // 목록 새로고침
      }

      if (failCount > 0) {
        setError(
          `${failCount}개의 전략을 가져오는데 실패했습니다:\n` + 
          errors.slice(0, 3).join('\n') +
          (errors.length > 3 ? `\n... 외 ${errors.length - 3}개` : '')
        );
      }

      setImportDialogOpen(false);
      setImportData(null);
    } catch (err: any) {
      setError('전략 가져오기 중 오류 발생: ' + (err.message || '알 수 없는 오류'));
    } finally {
      setImportLoading(false);
    }
  }, [importData, loadRules]);

  /**
   * 현재 탭의 모든 전략 삭제
   */
  const handleDeleteAll = useCallback(async () => {
    const currentRules = currentTrendTab === 'ALL' 
      ? rules.filter(r => r.trendType === 'ALL' || !r.trendType)
      : rules.filter(r => r.trendType === currentTrendTab);

    if (currentRules.length === 0) {
      setError('삭제할 전략이 없습니다.');
      return;
    }

    setDeletingAll(true);
    let successCount = 0;
    let failCount = 0;
    const errors: string[] = [];

    try {
      for (const rule of currentRules) {
        if (!rule.id) continue;
        
        try {
          await deleteStrategyRule(rule.id);
          successCount++;
        } catch (err: any) {
          failCount++;
          const errorMsg = err.response?.data?.message || err.message || '알 수 없는 오류';
          errors.push(`"${rule.name}": ${errorMsg}`);
        }
      }

      // 결과 표시
      if (successCount > 0) {
        setSuccess(`${successCount}개의 전략을 성공적으로 삭제했습니다.`);
        loadRules(); // 목록 새로고침
      }

      if (failCount > 0) {
        setError(
          `${failCount}개의 전략 삭제에 실패했습니다:\n` + 
          errors.slice(0, 3).join('\n') +
          (errors.length > 3 ? `\n... 외 ${errors.length - 3}개` : '')
        );
      }

      setDeleteAllDialogOpen(false);
    } catch (err: any) {
      setError('전략 삭제 중 오류 발생: ' + (err.message || '알 수 없는 오류'));
    } finally {
      setDeletingAll(false);
    }
  }, [currentTrendTab, rules, loadRules]);

  // 현재 탭에 맞는 규칙 개수
  const currentTabRulesCount = currentTrendTab === 'ALL'
    ? rules.filter(r => r.trendType === 'ALL' || !r.trendType).length
    : rules.filter(r => r.trendType === currentTrendTab).length;

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h5" fontWeight="bold">
          투자 전략 관리
        </Typography>
        <Box display="flex" gap={1}>
          <Button
            variant="outlined"
            startIcon={<FileDownloadIcon />}
            onClick={handleExport}
            disabled={rules.length === 0}
          >
            Export
          </Button>
          <Button
            variant="outlined"
            component="label"
            startIcon={<FileUploadIcon />}
          >
            Import
            <input
              type="file"
              hidden
              accept=".json"
              onChange={handleImportFile}
            />
          </Button>
          <Button
            variant="outlined"
            color="error"
            startIcon={<DeleteSweepIcon />}
            onClick={() => setDeleteAllDialogOpen(true)}
            disabled={currentTabRulesCount === 0}
          >
            전체삭제
          </Button>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={loadRules}
          >
            새로고침
          </Button>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={handleNewRule}
          >
            새 규칙 추가
          </Button>
                  </Box>
      </Box>

      {error && (
        <Alert severity="error" onClose={() => setError(null)} sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {success && (
        <Alert severity="success" onClose={() => setSuccess(null)} sx={{ mb: 2 }}>
          {success}
        </Alert>
      )}

      {/* 추세 타입 탭 */}
      <Paper sx={{ mb: 3 }}>
        <Tabs
          value={currentTrendTab}
          onChange={(_, newValue) => setCurrentTrendTab(newValue)}
          variant="scrollable"
          scrollButtons="auto"
          sx={{ borderBottom: 1, borderColor: 'divider' }}
        >
          {TREND_TYPES.map((trend) => (
            <Tab
              key={trend.value}
              value={trend.value}
              label={
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  {trend.icon}
                  <span>{trend.label}</span>
                  <Chip
                    label={getRuleCountByTrend(trend.value)}
                    size="small"
                    sx={{ 
                      bgcolor: trend.color,
                      color: 'white',
                      height: 20,
                      '& .MuiChip-label': { px: 1 }
                    }}
                  />
                </Box>
              }
            />
          ))}
        </Tabs>
                </Paper>

      {/* 현재 추세 설명 */}
      <Alert severity="info" sx={{ mb: 3 }}>
                  <Typography variant="body2">
          {currentTrendTab === 'ALL' && '모든 시장 상황에 적용되는 기본 전략 규칙입니다.'}
          {currentTrendTab === 'UPTREND' && '상승추세(정배열) 시장에서 적용되는 전략 규칙입니다. 이동평균선이 정배열 상태일 때 활성화됩니다.'}
          {currentTrendTab === 'DOWNTREND' && '하락추세(역배열) 시장에서 적용되는 전략 규칙입니다. 이동평균선이 역배열 상태일 때 활성화됩니다.'}
          {currentTrendTab === 'SIDEWAYS' && '횡보장에서 적용되는 전략 규칙입니다. 뚜렷한 방향성 없이 가격이 등락하는 상황에서 활성화됩니다.'}
          {currentTrendTab === 'RANGE' && '박스권 시장에서 적용되는 전략 규칙입니다. 가격이 일정 범위 내에서 움직이는 상황에서 활성화됩니다.'}
                  </Typography>
                </Alert>

      {/* 매수 전략 */}
      <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <TrendingUpIcon color="success" />
        매수 전략 ({buyRules.length}개)
                    </Typography>
      
      <Grid container spacing={2} sx={{ mb: 4 }}>
        {buyRules.map((rule) => (
          <Grid item xs={12} md={6} lg={4} key={rule.id}>
            <RuleCard 
              rule={rule} 
              onEdit={() => handleEditRule(rule)}
              onDelete={() => handleDeleteRule(rule.id!)}
              onToggle={() => handleToggleRule(rule.id!, rule.enabled ?? true)}
                    />
                  </Grid>
        ))}
        {buyRules.length === 0 && (
                  <Grid item xs={12}>
            <Alert severity="info">
              {currentTrendTab === 'ALL' ? '등록된 매수 전략이 없습니다.' : `${getTrendDisplayName(currentTrendTab)} 매수 전략이 없습니다.`}
              <Button size="small" onClick={handleNewRule} sx={{ ml: 2 }}>추가하기</Button>
            </Alert>
                  </Grid>
        )}
                  </Grid>

      {/* 매도 전략 */}
      <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <TrendingDownIcon color="error" />
        매도 전략 ({sellRules.length}개)
                    </Typography>

      <Grid container spacing={2}>
        {sellRules.map((rule) => (
          <Grid item xs={12} md={6} lg={4} key={rule.id}>
            <RuleCard 
              rule={rule} 
              onEdit={() => handleEditRule(rule)}
              onDelete={() => handleDeleteRule(rule.id!)}
              onToggle={() => handleToggleRule(rule.id!, rule.enabled ?? true)}
                    />
                  </Grid>
        ))}
        {sellRules.length === 0 && (
                  <Grid item xs={12}>
            <Alert severity="info">
              {currentTrendTab === 'ALL' ? '등록된 매도 전략이 없습니다.' : `${getTrendDisplayName(currentTrendTab)} 매도 전략이 없습니다.`}
              <Button size="small" onClick={handleNewRule} sx={{ ml: 2 }}>추가하기</Button>
            </Alert>
                  </Grid>
        )}
                  </Grid>

      {/* 규칙 편집 다이얼로그 */}
      <RuleEditDialog
        open={dialogOpen}
        rule={editingRule}
        isNew={isNewRule}
        existingRules={rules}
        onClose={() => { setDialogOpen(false); setEditingRule(null); }}
        onChange={(rule) => setEditingRule(rule)}
        onSave={handleSaveRule}
      />

      {/* Import 확인 다이얼로그 */}
      <Dialog 
        open={importDialogOpen} 
        onClose={() => !importLoading && setImportDialogOpen(false)} 
        maxWidth="md" 
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <FileUploadIcon color="primary" />
            전략 가져오기 확인
          </Box>
        </DialogTitle>
        <DialogContent>
          <Alert severity="info" sx={{ mb: 2 }}>
            다음 {importData?.length || 0}개의 전략을 가져옵니다.
          </Alert>
          
          {importData && (
            <TableContainer component={Paper} variant="outlined" sx={{ maxHeight: 400 }}>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell><strong>전략명</strong></TableCell>
                    <TableCell align="center"><strong>신호</strong></TableCell>
                    <TableCell align="center"><strong>추세</strong></TableCell>
                    <TableCell align="center"><strong>조건 수</strong></TableCell>
                    <TableCell align="center"><strong>활성화</strong></TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {importData.map((rule, index) => (
                    <TableRow key={index}>
                      <TableCell>{rule.name}</TableCell>
                      <TableCell align="center">
                        <Chip
                          label={rule.signalType === 'BUY' ? '매수' : '매도'}
                          color={rule.signalType === 'BUY' ? 'success' : 'error'}
                          size="small"
                        />
                      </TableCell>
                      <TableCell align="center">
                        {getTrendDisplayName(rule.trendType || 'ALL')}
                      </TableCell>
                      <TableCell align="center">
                        {rule.totalConditionCount || 
                         (rule.buyConditionGroups?.reduce((sum, g) => sum + g.conditions.length, 0) || 0) +
                         (rule.sellConditionGroups?.reduce((sum, g) => sum + g.conditions.length, 0) || 0)}
                      </TableCell>
                      <TableCell align="center">
                        {rule.enabled !== false ? '✓' : '✗'}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          )}

          <Alert severity="warning" sx={{ mt: 2 }}>
            <strong>주의:</strong> 가져온 전략은 새로운 전략으로 추가됩니다. 기존 전략은 삭제되지 않습니다.
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button 
            onClick={() => setImportDialogOpen(false)} 
            disabled={importLoading}
          >
            취소
          </Button>
          <Button
            variant="contained"
            onClick={handleConfirmImport}
            disabled={importLoading}
            startIcon={importLoading ? <CircularProgress size={16} /> : <FileUploadIcon />}
          >
            {importLoading ? '가져오는 중...' : `${importData?.length || 0}개 전략 가져오기`}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 전체삭제 확인 다이얼로그 */}
      <Dialog 
        open={deleteAllDialogOpen} 
        onClose={() => !deletingAll && setDeleteAllDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: 'error.main' }}>
            <DeleteSweepIcon />
            전체 전략 삭제
          </Box>
        </DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 2 }}>
            <strong>경고:</strong> 이 작업은 되돌릴 수 없습니다!
          </Alert>
          <Typography variant="body1" gutterBottom>
            현재 <strong>{getTrendDisplayName(currentTrendTab)}</strong> 탭의 모든 전략 <strong>{currentTabRulesCount}개</strong>를 삭제하시겠습니까?
          </Typography>
          <Box sx={{ mt: 2, p: 2, bgcolor: 'grey.100', borderRadius: 1 }}>
            <Typography variant="body2" color="text.secondary">
              삭제될 전략:
            </Typography>
            <Box sx={{ maxHeight: 200, overflow: 'auto', mt: 1 }}>
              {filteredRules.map((rule, index) => (
                <Typography key={rule.id || index} variant="body2" sx={{ py: 0.5 }}>
                  • {rule.name} ({rule.signalType === 'BUY' ? '매수' : '매도'})
                </Typography>
              ))}
            </Box>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button 
            onClick={() => setDeleteAllDialogOpen(false)} 
            disabled={deletingAll}
          >
            취소
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleDeleteAll}
            disabled={deletingAll}
            startIcon={deletingAll ? <CircularProgress size={16} /> : <DeleteSweepIcon />}
          >
            {deletingAll ? '삭제 중...' : `${currentTabRulesCount}개 전략 모두 삭제`}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

interface RuleCardProps {
  rule: StrategyRuleDto;
  onEdit: () => void;
  onDelete: () => void;
  onToggle: () => void;
}

const RuleCard: React.FC<RuleCardProps> = ({ rule, onEdit, onDelete, onToggle }) => {
  const trendInfo = TREND_TYPES.find(t => t.value === (rule.trendType || 'ALL'));

  return (
    <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <CardContent sx={{ flexGrow: 1 }}>
        <Box display="flex" justifyContent="space-between" alignItems="flex-start" mb={1}>
          <Typography variant="h6" component="div" sx={{ fontWeight: 'bold' }}>
            {rule.name}
          </Typography>
          <Chip
            label={rule.enabled ? '활성' : '비활성'}
            color={rule.enabled ? 'success' : 'default'}
            size="small"
                  />
                </Box>

        <Box display="flex" gap={1} mb={2}>
          <Chip
            icon={rule.signalType === 'BUY' ? <TrendingUpIcon /> : <TrendingDownIcon />}
            label={rule.signalType === 'BUY' ? '매수' : '매도'}
            color={rule.signalType === 'BUY' ? 'success' : 'error'}
            size="small"
            variant="outlined"
          />
          {trendInfo && (
            <Chip
              icon={trendInfo.icon as React.ReactElement}
              label={trendInfo.label}
              size="small"
              variant="outlined"
              sx={{ borderColor: trendInfo.color, color: trendInfo.color }}
            />
          )}
        </Box>

        {rule.description && (
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            {rule.description}
                      </Typography>
        )}

        <Typography variant="caption" color="text.secondary">
          조건: {rule.totalConditionCount ?? 0}개
        </Typography>
      </CardContent>

      <CardActions sx={{ justifyContent: 'space-between' }}>
                  <FormControlLabel
                    control={
                      <Switch
              checked={rule.enabled ?? true}
              onChange={onToggle}
              size="small"
            />
          }
          label={rule.enabled ? '활성화됨' : '비활성화됨'}
        />
        <Box>
          <Tooltip title="수정">
            <IconButton onClick={onEdit} size="small">
              <EditIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Tooltip title="삭제">
            <IconButton onClick={onDelete} size="small" color="error">
              <DeleteIcon fontSize="small" />
            </IconButton>
          </Tooltip>
                </Box>
      </CardActions>
    </Card>
  );
};

export default TradingStrategyTab;
