import React from 'react';
import {
  Box,
  Paper,
  Typography,
  Divider,
  Chip,
  useTheme,
  Alert,
} from '@mui/material';
import {
  Description as DescriptionIcon,
  CheckCircle as CheckIcon,
  Error as ErrorIcon,
} from '@mui/icons-material';
import { LogicNode, nodeToNaturalLanguage, countNodes, countConditions, getMaxDepth } from '../../services/strategyDSLApi';

// ============================================================
// Props 정의
// ============================================================

export interface NaturalLanguagePreviewProps {
  rootNode: LogicNode | null;
  strategyName?: string;
}

// ============================================================
// NaturalLanguagePreview 컴포넌트
// ============================================================

const NaturalLanguagePreview: React.FC<NaturalLanguagePreviewProps> = ({
  rootNode,
  strategyName,
}) => {
  const theme = useTheme();

  // 통계 계산
  const stats = rootNode ? {
    totalNodes: countNodes(rootNode),
    conditionCount: countConditions(rootNode),
    maxDepth: getMaxDepth(rootNode),
  } : null;

  // 복잡도 점수 계산 (1-10)
  const calculateComplexity = (): number => {
    if (!stats) return 0;
    
    const score = (stats.totalNodes * 2) + (stats.maxDepth * 3) + stats.conditionCount;
    return Math.min(10, Math.max(1, Math.floor(score / 5)));
  };

  const complexity = calculateComplexity();

  // 복잡도에 따른 색상
  const getComplexityColor = () => {
    if (complexity <= 3) return theme.palette.success.main;
    if (complexity <= 6) return theme.palette.warning.main;
    return theme.palette.error.main;
  };

  // 복잡도에 따른 라벨
  const getComplexityLabel = () => {
    if (complexity <= 3) return '간단함';
    if (complexity <= 6) return '보통';
    return '복잡함';
  };

  // 자연어 변환
  const naturalText = rootNode ? nodeToNaturalLanguage(rootNode) : '';

  return (
    <Paper
      elevation={3}
      sx={{
        p: 2,
        height: '100%',
        overflow: 'auto',
        backgroundColor: theme.palette.mode === 'dark' ? 
          theme.palette.grey[900] : 
          theme.palette.grey[50],
      }}
    >
      <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <DescriptionIcon color="primary" />
        전략 미리보기
      </Typography>

      {strategyName && (
        <Typography variant="subtitle2" color="text.secondary" gutterBottom sx={{ mb: 2 }}>
          {strategyName}
        </Typography>
      )}

      <Divider sx={{ mb: 2 }} />

      {/* 통계 정보 */}
      {stats && (
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle2" gutterBottom fontWeight="bold">
            📊 통계
          </Typography>
          <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mb: 2 }}>
            <Chip
              label={`노드: ${stats.totalNodes}개`}
              size="small"
              color="default"
            />
            <Chip
              label={`조건: ${stats.conditionCount}개`}
              size="small"
              color="primary"
            />
            <Chip
              label={`깊이: ${stats.maxDepth}`}
              size="small"
              color="secondary"
            />
            <Chip
              label={`복잡도: ${getComplexityLabel()} (${complexity}/10)`}
              size="small"
              sx={{
                backgroundColor: getComplexityColor(),
                color: theme.palette.getContrastText(getComplexityColor()),
              }}
            />
          </Box>
        </Box>
      )}

      <Divider sx={{ mb: 2 }} />

      {/* 자연어 설명 */}
      {rootNode ? (
        <Box>
          <Typography variant="subtitle2" gutterBottom fontWeight="bold">
            📝 설명
          </Typography>
          <Paper
            sx={{
              p: 2,
              backgroundColor: theme.palette.mode === 'dark' ? 
                theme.palette.grey[800] : 
                theme.palette.background.default,
              border: `1px solid ${theme.palette.divider}`,
              fontFamily: 'monospace',
              fontSize: '0.9rem',
              lineHeight: 1.8,
              whiteSpace: 'pre-wrap',
              color: theme.palette.text.primary,
            }}
          >
            {naturalText || '조건이 없습니다'}
          </Paper>

          {/* 유효성 알림 */}
          {stats && stats.conditionCount > 0 && (
            <Alert
              severity="success"
              icon={<CheckIcon />}
              sx={{ mt: 2 }}
            >
              전략이 유효합니다! 저장 가능합니다.
            </Alert>
          )}

          {stats && stats.conditionCount === 0 && (
            <Alert
              severity="warning"
              icon={<ErrorIcon />}
              sx={{ mt: 2 }}
            >
              조건을 최소 1개 이상 추가해주세요.
            </Alert>
          )}

          {/* 복잡도 경고 */}
          {complexity > 7 && (
            <Alert
              severity="warning"
              sx={{ mt: 2 }}
            >
              전략이 복잡합니다. 백테스트 성능이 저하될 수 있습니다.
            </Alert>
          )}
        </Box>
      ) : (
        <Box
          sx={{
            p: 4,
            textAlign: 'center',
            color: theme.palette.text.secondary,
          }}
        >
          <DescriptionIcon sx={{ fontSize: 60, mb: 2, opacity: 0.3 }} />
          <Typography variant="body2">
            전략 노드를 추가하면 여기에 미리보기가 표시됩니다
          </Typography>
        </Box>
      )}

      {/* 가이드 */}
      <Box
        sx={{
          mt: 3,
          p: 2,
          backgroundColor: theme.palette.mode === 'dark' ?
            theme.palette.grey[800] :
            theme.palette.info.light + '20',
          borderRadius: 1,
          border: `1px solid ${theme.palette.info.main}`,
        }}
      >
        <Typography variant="subtitle2" color="info.main" gutterBottom fontWeight="bold">
          💡 자연어 설명이란?
        </Typography>
        <Typography variant="caption" component="div" sx={{ mb: 0.5 }}>
          • 전략을 사람이 읽기 쉬운 문장으로 변환합니다
        </Typography>
        <Typography variant="caption" component="div" sx={{ mb: 0.5 }}>
          • AND/OR/NOT 논리 구조를 명확히 표현합니다
        </Typography>
        <Typography variant="caption" component="div">
          • 조건별로 들여쓰기되어 계층 구조를 확인할 수 있습니다
        </Typography>
      </Box>

      {/* 예시 */}
      {!rootNode && (
        <Box
          sx={{
            mt: 2,
            p: 2,
            backgroundColor: theme.palette.mode === 'dark' ?
              theme.palette.grey[800] :
              theme.palette.success.light + '20',
            borderRadius: 1,
            border: `1px solid ${theme.palette.success.main}`,
          }}
        >
          <Typography variant="subtitle2" color="success.main" gutterBottom fontWeight="bold">
            📖 예시
          </Typography>
          <Typography variant="caption" component="div" sx={{ fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}>
{`다음 조건을 모두 만족:
  CCI(20)가 -100을 상향 돌파
  RSI(14)가 30 이하`}
          </Typography>
        </Box>
      )}
    </Paper>
  );
};

export default NaturalLanguagePreview;
