import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Box,
  Typography,
  Divider,
  Alert,
  useTheme,
} from '@mui/material';
import { Save as SaveIcon, Close as CloseIcon } from '@mui/icons-material';
import { ConditionDSL } from '../../services/strategyDSLApi';

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

export interface ConditionEditorProps {
  open: boolean;
  condition: ConditionDSL | null;
  onSave: (condition: ConditionDSL) => void;
  onClose: () => void;
}

// ============================================================
// 지표 및 조건 타입 옵션
// ============================================================

const INDICATOR_OPTIONS = [
  { value: 'CCI', label: 'CCI (Commodity Channel Index)' },
  { value: 'MACD', label: 'MACD (Moving Average Convergence Divergence)' },
  { value: 'RSI', label: 'RSI (Relative Strength Index)' },
  { value: 'STOCHASTIC', label: 'Stochastic Oscillator' },
  { value: 'ADX', label: 'ADX (Average Directional Index)' },
  { value: 'TRIX', label: 'TRIX' },
  { value: 'DMI', label: 'DMI (Directional Movement Index)' },
  { value: 'OBV', label: 'OBV (On Balance Volume)' },
  { value: 'BWI', label: '볼린저 밴드 %B' },
  { value: 'VOLUME', label: '거래량' },
  { value: 'DISPARITY', label: '이격도' },
  { value: 'WILLIAMS_R', label: 'Williams %R' },
];

const CONDITION_OPTIONS = [
  { value: 'CROSS_UP', label: '상향 돌파 (Cross Up)', requiresTarget: true },
  { value: 'CROSS_DOWN', label: '하향 돌파 (Cross Down)', requiresTarget: true },
  { value: 'GOLDEN_CROSS', label: '골든 크로스', requiresTarget: false },
  { value: 'DEAD_CROSS', label: '데드 크로스', requiresTarget: false },
  { value: 'ABOVE', label: '이상 (≥)', requiresTarget: true },
  { value: 'BELOW', label: '이하 (≤)', requiresTarget: true },
  { value: 'ABOVE_STRICT', label: '초과 (>)', requiresTarget: true },
  { value: 'BELOW_STRICT', label: '미만 (<)', requiresTarget: true },
  { value: 'BETWEEN', label: '범위 내', requiresTarget: true, requiresSecondary: true },
  { value: 'OVERBOUGHT', label: '과매수', requiresTarget: false },
  { value: 'OVERSOLD', label: '과매도', requiresTarget: false },
  { value: 'INCREASING', label: '상승 중', requiresTarget: false },
  { value: 'DECREASING', label: '하락 중', requiresTarget: false },
  // 구름 조건 - 일목균형도의 구름 신호 (기본값으로 고정)
  { value: 'CLOUD_TOP', label: '구름위 (Cloud Top)', requiresTarget: false, disabledSecondary: true },
];

// ============================================================
// ConditionEditor 컴포넌트
// ============================================================

const ConditionEditor: React.FC<ConditionEditorProps> = ({
  open,
  condition,
  onSave,
  onClose,
}) => {
  const theme = useTheme();

  // 편집 상태
  const [indicatorType, setIndicatorType] = useState('CCI');
  const [conditionType, setConditionType] = useState('CROSS_UP');
  const [targetValue, setTargetValue] = useState<number>(-100);
  const [secondaryValue, setSecondaryValue] = useState<number | undefined>(undefined);
  const [period, setPeriod] = useState<number>(20);
  const [comparePeriod, setComparePeriod] = useState<number | undefined>(undefined);
  const [description, setDescription] = useState('');

  // 초기 데이터 로드
  useEffect(() => {
    if (condition) {
      setIndicatorType(condition.indicatorType || 'CCI');
      setConditionType(condition.conditionType || 'CROSS_UP');
      setTargetValue(condition.targetValue ?? -100);
      setSecondaryValue(condition.secondaryValue);
      setPeriod(condition.period ?? 20);
      setComparePeriod(condition.comparePeriod);
      setDescription('');
    } else {
      // 기본값
      setIndicatorType('CCI');
      setConditionType('CROSS_UP');
      setTargetValue(-100);
      setSecondaryValue(undefined);
      setPeriod(20);
      setComparePeriod(undefined);
      setDescription('');
    }
  }, [condition]);

  // 선택된 조건 타입 정보
  const selectedCondition = CONDITION_OPTIONS.find(opt => opt.value === conditionType);

  // 저장 핸들러
  const handleSave = () => {
    const newCondition: ConditionDSL = {
      indicatorType,
      conditionType,
      targetValue: selectedCondition?.requiresTarget ? targetValue : undefined,
      secondaryValue: selectedCondition?.requiresSecondary ? secondaryValue : undefined,
      period,
      comparePeriod,
    };

    onSave(newCondition);
    onClose();
  };

  // 유효성 검증
  const isValid = () => {
    if (!indicatorType || !conditionType) return false;
    
    if (selectedCondition?.requiresTarget && targetValue === undefined) return false;
    
    if (selectedCondition?.requiresSecondary && secondaryValue === undefined) return false;
    
    return true;
  };

  // 기본 기간값 추천
  const getRecommendedPeriod = (indicator: string): number => {
    const recommendations: Record<string, number> = {
      CCI: 20,
      MACD: 12,
      RSI: 14,
      STOCHASTIC: 14,
      ADX: 14,
      TRIX: 12,
      DMI: 14,
      OBV: 20,
      BWI: 20,
      VOLUME: 20,
      DISPARITY: 20,
      WILLIAMS_R: 14,
    };
    return recommendations[indicator] || 20;
  };

  // 지표 변경 시 기간 자동 설정
  const handleIndicatorChange = (value: string) => {
    setIndicatorType(value);
    setPeriod(getRecommendedPeriod(value));
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          backgroundColor: theme.palette.background.paper,
        },
      }}
    >
      <DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Typography variant="h6" component="span">
          조건 설정
        </Typography>
      </DialogTitle>

      <DialogContent dividers>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          {/* 지표 선택 */}
          <FormControl fullWidth>
            <InputLabel>지표 타입</InputLabel>
            <Select
              value={indicatorType}
              onChange={(e) => handleIndicatorChange(e.target.value)}
              label="지표 타입"
            >
              {INDICATOR_OPTIONS.map((opt) => (
                <MenuItem key={opt.value} value={opt.value}>
                  {opt.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          {/* 조건 타입 선택 */}
          <FormControl fullWidth>
            <InputLabel>조건 타입</InputLabel>
            <Select
              value={conditionType}
              onChange={(e) => setConditionType(e.target.value)}
              label="조건 타입"
            >
              {CONDITION_OPTIONS.map((opt) => (
                <MenuItem key={opt.value} value={opt.value}>
                  {opt.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          {/* 기준값 입력 (조건에 따라 표시) */}
          {selectedCondition?.requiresTarget && (
            <TextField
              label="기준값"
              type="number"
              value={targetValue}
              onChange={(e) => setTargetValue(Number(e.target.value))}
              fullWidth
              disabled={selectedCondition?.disabledSecondary ? true : false}
              helperText={selectedCondition?.disabledSecondary ? "구름 조건은 읽기 전용입니다." : "예: CCI -100, RSI 30"}
            />
          )}

          {/* 보조 기준값 입력 (BETWEEN 조건) */}
          {selectedCondition?.requiresSecondary && !selectedCondition?.disabledSecondary && (
            <TextField
              label="보조 기준값"
              type="number"
              value={secondaryValue ?? ''}
              onChange={(e) => setSecondaryValue(Number(e.target.value))}
              fullWidth
              helperText="범위의 상한값"
            />
          )}
          {selectedCondition?.disabledSecondary && (
            <Alert severity="info" sx={{ m: 1 }}>
              구림위/구름위는 현재 일목균형도 설정에서 자동으로 계산되므로 변경할 수 없습니다.
            </Alert>
          )}

          <Divider />

          {/* 기간 설정 */}
          <TextField
            label="기간"
            type="number"
            value={period}
            onChange={(e) => setPeriod(Number(e.target.value))}
            fullWidth
            helperText={`권장: ${getRecommendedPeriod(indicatorType)}`}
          />

          {/* 비교 기간 (골든/데드 크로스용) */}
          {(conditionType === 'GOLDEN_CROSS' || conditionType === 'DEAD_CROSS') && (
            <TextField
              label="비교 기간 (장기)"
              type="number"
              value={comparePeriod ?? ''}
              onChange={(e) => setComparePeriod(Number(e.target.value))}
              fullWidth
              helperText="예: MACD 골든 크로스의 경우 26"
            />
          )}

          {/* 미리보기 */}
          <Alert severity="info" sx={{ mt: 2 }}>
            <Typography variant="body2" fontWeight="bold" gutterBottom>
              미리보기
            </Typography>
            <Typography variant="body2">
              {indicatorType}
              {period && `(${period})`}
              {conditionType === 'CROSS_UP' && ` 가 ${targetValue}을 상향 돌파`}
              {conditionType === 'CROSS_DOWN' && ` 가 ${targetValue}을 하향 돌파`}
              {conditionType === 'GOLDEN_CROSS' && ' 골든 크로스'}
              {conditionType === 'DEAD_CROSS' && ' 데드 크로스'}
              {conditionType === 'ABOVE' && ` ≥ ${targetValue}`}
              {conditionType === 'BELOW' && ` ≤ ${targetValue}`}
              {conditionType === 'ABOVE_STRICT' && ` > ${targetValue}`}
              {conditionType === 'BELOW_STRICT' && ` < ${targetValue}`}
              {conditionType === 'BETWEEN' && ` ${targetValue} ~ ${secondaryValue} 사이`}
              {conditionType === 'OVERBOUGHT' && ' 과매수'}
              {conditionType === 'OVERSOLD' && ' 과매도'}
              {conditionType === 'INCREASING' && ' 상승 중'}
              {conditionType === 'DECREASING' && ' 하락 중'}
            </Typography>
          </Alert>
        </Box>
      </DialogContent>

      <DialogActions>
        <Button
          onClick={onClose}
          startIcon={<CloseIcon />}
          color="inherit"
        >
          취소
        </Button>
        <Button
          onClick={handleSave}
          startIcon={<SaveIcon />}
          variant="contained"
          disabled={!isValid()}
        >
          저장
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ConditionEditor;
