import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  Typography,
  Accordion,
  AccordionSummary,
  AccordionDetails,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import {
  addGlobalCondition,
  updateCondition,
  AlertConditionDto,
  IndicatorType,
  ConditionType,
} from '../../services/alertApi';
import { loadIndicatorSettingsFromStorage } from '../../contexts/IndicatorSettingsContext';

interface GlobalAlertConditionEditorProps {
  condition?: AlertConditionDto | null;
  onSave: () => void;
  onCancel: () => void;
}

// 지표 옵션
const INDICATOR_OPTIONS: { value: IndicatorType; label: string }[] = [
  { value: 'MACD', label: 'MACD' },
  { value: 'RSI', label: 'RSI' },
  { value: 'STOCHASTIC', label: 'Stochastic' },
  { value: 'CCI', label: 'CCI' },
  { value: 'VOLUME', label: '거래량' },
  { value: 'OBV', label: 'OBV' },
  { value: 'WILLIAMS_R', label: 'Williams %R' },
  { value: 'VR', label: 'VR' },
  { value: 'ADX', label: 'ADX' },
  { value: 'TRIX', label: 'TRIX' },
  { value: 'DISPARITY', label: '이격도' },
];

// 조건 타입별 라벨
const CONDITION_LABELS: Record<ConditionType, string> = {
  CROSS_UP: '상향 돌파',
  CROSS_DOWN: '하향 돌파',
  ABOVE: '초과',
  BELOW: '미만',
  BETWEEN: '범위 내',
  EQUAL: '같음',
  ZERO_CROSS_UP: '0선 상향 돌파',
  ZERO_CROSS_DOWN: '0선 하향 돌파',
  SIGNAL_CROSS_UP: '시그널선 상향 돌파',
  SIGNAL_CROSS_DOWN: '시그널선 하향 돌파',
  HISTOGRAM_POSITIVE: '히스토그램 양수',
  HISTOGRAM_NEGATIVE: '히스토그램 음수',
  HISTOGRAM_INCREASE: '히스토그램 증가',
  HISTOGRAM_DECREASE: '히스토그램 감소',
  K_CROSS_D_UP: '%K가 %D 상향돌파',
  K_CROSS_D_DOWN: '%K가 %D 하향돌파',
  VOLUME_SPIKE: '거래량 급증',
  VOLUME_ABOVE_AVG: '평균 이상',
  VOLUME_BELOW_AVG: '평균 이하',
  INCREASE: '증가',
  DECREASE: '감소',
  GOLDEN_CROSS: '골든크로스',
  DEAD_CROSS: '데드크로스',
};

// 지표별 허용 조건
const INDICATOR_CONDITIONS: Partial<Record<IndicatorType, ConditionType[]>> = {
  MACD: ['ZERO_CROSS_UP', 'ZERO_CROSS_DOWN', 'SIGNAL_CROSS_UP', 'SIGNAL_CROSS_DOWN', 
         'HISTOGRAM_POSITIVE', 'HISTOGRAM_NEGATIVE', 'HISTOGRAM_INCREASE', 'HISTOGRAM_DECREASE'],
  RSI: ['ABOVE', 'BELOW', 'BETWEEN', 'CROSS_UP', 'CROSS_DOWN'],
  STOCHASTIC: ['ABOVE', 'BELOW', 'BETWEEN', 'K_CROSS_D_UP', 'K_CROSS_D_DOWN'],
  CCI: ['ABOVE', 'BELOW', 'ZERO_CROSS_UP', 'ZERO_CROSS_DOWN'],
  VOLUME: ['VOLUME_SPIKE', 'VOLUME_ABOVE_AVG', 'VOLUME_BELOW_AVG'],
  OBV: ['INCREASE', 'DECREASE', 'CROSS_UP', 'CROSS_DOWN'],
  WILLIAMS_R: ['ABOVE', 'BELOW', 'BETWEEN'],
  VR: ['ABOVE', 'BELOW', 'BETWEEN'],
  ADX: ['ABOVE', 'BELOW'],
  TRIX: ['ZERO_CROSS_UP', 'ZERO_CROSS_DOWN', 'ABOVE', 'BELOW'],
  DISPARITY: ['ABOVE', 'BELOW', 'BETWEEN'],
};

/**
 * 전역 알림 조건 에디터
 */
const GlobalAlertConditionEditor: React.FC<GlobalAlertConditionEditorProps> = ({
  condition,
  onSave,
  onCancel,
}) => {
  const [formData, setFormData] = useState<AlertConditionDto>({
    indicatorType: 'RSI',
    conditionType: 'ABOVE',
    targetValue: undefined,
    secondaryValue: undefined,
    period: undefined,
    enabled: true,
    orderIndex: 0,
    description: '',
    logicalOperator: 'OR', // 기본값 OR
  });

  const [saving, setSaving] = useState(false);
  const indicatorSettings = loadIndicatorSettingsFromStorage();

  useEffect(() => {
    if (condition) {
      setFormData({
        ...condition,
        logicalOperator: 'OR', // OR로 고정
      });
    }
  }, [condition]);

  const handleChange = (field: keyof AlertConditionDto, value: any) => {
    setFormData(prev => {
      const updated = { ...prev, [field]: value };
      
      // 지표 변경 시 조건 타입 초기화
      if (field === 'indicatorType') {
        const newConditions = INDICATOR_CONDITIONS[value as IndicatorType] || [];
        updated.conditionType = newConditions[0] || 'ABOVE';
        updated.targetValue = undefined;
        updated.secondaryValue = undefined;
        updated.period = getDefaultPeriod(value as IndicatorType);
      }
      
      // 조건 타입 변경 시 값 초기화
      if (field === 'conditionType') {
        if (!needsTargetValue(updated.indicatorType, value as ConditionType)) {
          updated.targetValue = undefined;
        }
        if (value !== 'BETWEEN') {
          updated.secondaryValue = undefined;
        }
      }
      
      return updated;
    });
  };

  const getDefaultPeriod = (indicatorType: IndicatorType): number | undefined => {
    switch (indicatorType) {
      case 'RSI': return indicatorSettings.rsiPeriod || 14;
      case 'STOCHASTIC': return indicatorSettings.stochasticKPeriod || 12;
      case 'CCI': return indicatorSettings.cciPeriod || 14;
      case 'MACD': return indicatorSettings.macdSignalPeriod || 9;
      case 'WILLIAMS_R': return indicatorSettings.williamsRPeriod || 14;
      case 'ADX': return 14;
      case 'TRIX': return indicatorSettings.trixPeriod || 12;
      case 'DISPARITY': return indicatorSettings.disparityShortPeriod || 5;
      default: return undefined;
    }
  };

  const needsTargetValue = (indicatorType: IndicatorType, conditionType: ConditionType): boolean => {
    if (indicatorType === 'MACD') return false;
    return ['ABOVE', 'BELOW', 'BETWEEN', 'CROSS_UP', 'CROSS_DOWN'].includes(conditionType);
  };

  const needsSecondaryValue = (): boolean => {
    return formData.conditionType === 'BETWEEN';
  };

  const needsPeriod = (indicatorType: IndicatorType): boolean => {
    return ['RSI', 'STOCHASTIC', 'CCI', 'WILLIAMS_R', 'MACD', 'ADX', 'TRIX', 'DISPARITY', 'VR', 'OBV'].includes(indicatorType);
  };

  // 기간 옵션 (지표별)
  const getPeriodOptions = () => {
    switch (formData.indicatorType) {
      case 'MACD':
        return [{ value: indicatorSettings.macdSignalPeriod, label: 'MACD선' }];
      case 'STOCHASTIC':
        return [
          { value: indicatorSettings.stochasticKPeriod, label: '%K' },
          { value: indicatorSettings.stochasticDPeriod, label: '%D' },
        ];
      case 'RSI':
        return [{ value: indicatorSettings.rsiPeriod, label: 'RSI' }];
      case 'CCI':
        return [{ value: indicatorSettings.cciPeriod, label: 'CCI' }];
      case 'TRIX':
        return [{ value: indicatorSettings.trixPeriod, label: 'TRIX' }];
      case 'WILLIAMS_R':
        return [{ value: indicatorSettings.williamsRPeriod, label: 'Williams %R' }];
      case 'DISPARITY':
        return [
          { value: indicatorSettings.disparityUltraShortPeriod, label: '초단기' },
          { value: indicatorSettings.disparityShortPeriod, label: '단기' },
          { value: indicatorSettings.disparityMidPeriod, label: '중기' },
          { value: indicatorSettings.disparityLongPeriod, label: '장기' },
        ];
      case 'ADX':
        return [{ value: 14, label: 'ADX' }];
      case 'VR':
        return [{ value: 26, label: 'VR' }];
      default:
        return [];
    }
  };

  // 기준값 프리셋 옵션
  const getTargetValueOptions = () => {
    switch (formData.indicatorType) {
      case 'RSI':
        return [
          { value: indicatorSettings.rsiOversold, label: `침체이탈(${indicatorSettings.rsiOversold})` },
          { value: indicatorSettings.rsiMiddle, label: `중립(${indicatorSettings.rsiMiddle})` },
          { value: indicatorSettings.rsiOverbought, label: `과열진입(${indicatorSettings.rsiOverbought})` },
        ];
      case 'STOCHASTIC':
        return [
          { value: indicatorSettings.stochasticOversold, label: `침체이탈(${indicatorSettings.stochasticOversold})` },
          { value: 50, label: '중립(50)' },
          { value: indicatorSettings.stochasticOverbought, label: `과열진입(${indicatorSettings.stochasticOverbought})` },
        ];
      case 'CCI':
        return [
          { value: indicatorSettings.cciOversold, label: `침체이탈(${indicatorSettings.cciOversold})` },
          { value: indicatorSettings.cciMiddle, label: `중립(${indicatorSettings.cciMiddle})` },
          { value: indicatorSettings.cciOverbought, label: `과열진입(${indicatorSettings.cciOverbought})` },
        ];
      case 'WILLIAMS_R':
        return [
          { value: -80, label: '침체이탈(-80)' },
          { value: -50, label: '중립(-50)' },
          { value: -20, label: '과열진입(-20)' },
        ];
      case 'VR':
        return [
          { value: 150, label: '침체(150)' },
          { value: 250, label: '정상(250)' },
          { value: 350, label: '과열(350)' },
        ];
      case 'ADX':
        return [
          { value: 20, label: '약한추세(20)' },
          { value: 40, label: '강한추세(40)' },
        ];
      default:
        return [];
    }
  };

  const handleSubmit = async () => {
    try {
      setSaving(true);
      
      const dataToSave: AlertConditionDto = {
        ...formData,
        logicalOperator: 'OR' as 'OR', // OR로 강제 설정
      };
      
      if (condition?.id) {
        // 수정
        await updateCondition(condition.id, dataToSave);
      } else {
        // 추가
        await addGlobalCondition(dataToSave);
      }
      
      onSave();
    } catch (error) {
      console.error('조건 저장 실패:', error);
      alert('조건 저장에 실패했습니다.');
    } finally {
      setSaving(false);
    }
  };

  const availableConditions = INDICATOR_CONDITIONS[formData.indicatorType] || [];
  const periodOptions = getPeriodOptions();
  const targetValueOptions = getTargetValueOptions();
  const showTargetValue = needsTargetValue(formData.indicatorType, formData.conditionType);
  const showSecondaryValue = needsSecondaryValue();
  const showPeriod = needsPeriod(formData.indicatorType);

  return (
    <>
      <DialogTitle>
        {condition ? '전역 조건 수정' : '전역 조건 추가'}
      </DialogTitle>
      
      <DialogContent>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
          이 조건은 좌측에서 활성화된 모든 종목에 적용됩니다.
          <br />
          여러 조건을 추가하면 OR 조건으로 동작합니다 (하나라도 만족하면 알림).
        </Typography>
        
        <Grid container spacing={2}>
          {/* 지표 선택 */}
          <Grid item xs={12} sm={6} md={3}>
            <FormControl fullWidth size="small">
              <InputLabel>지표</InputLabel>
              <Select
                value={formData.indicatorType}
                label="지표"
                onChange={(e) => handleChange('indicatorType', e.target.value as IndicatorType)}
              >
                {INDICATOR_OPTIONS.map(opt => (
                  <MenuItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          {/* 기준선 (기간) */}
          {showPeriod && (
            <Grid item xs={12} sm={6} md={3}>
              <FormControl fullWidth size="small">
                <InputLabel>기준선</InputLabel>
                <Select
                  value={formData.period || ''}
                  label="기준선"
                  onChange={(e) => handleChange('period', parseInt(e.target.value as string))}
                >
                  {periodOptions.map(opt => (
                    <MenuItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
          )}

          {/* 조건 선택 */}
          <Grid item xs={12} sm={6} md={3}>
            <FormControl fullWidth size="small">
              <InputLabel>조건</InputLabel>
              <Select
                value={formData.conditionType}
                label="조건"
                onChange={(e) => handleChange('conditionType', e.target.value as ConditionType)}
              >
                {availableConditions.map(condType => (
                  <MenuItem key={condType} value={condType}>
                    {CONDITION_LABELS[condType]}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          {/* 기준값 */}
          {showTargetValue && (
            <Grid item xs={12} sm={6} md={3}>
              <FormControl fullWidth size="small">
                <InputLabel>기준값</InputLabel>
                <Select
                  value={formData.targetValue || ''}
                  label="기준값"
                  onChange={(e) => handleChange('targetValue', parseFloat(e.target.value as string))}
                >
                  {targetValueOptions.map(opt => (
                    <MenuItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </MenuItem>
                  ))}
                  <MenuItem value="custom">직접 입력</MenuItem>
                </Select>
              </FormControl>
              {formData.targetValue === undefined || 
               !targetValueOptions.some(opt => opt.value === formData.targetValue) ? (
                <TextField
                  fullWidth
                  size="small"
                  type="number"
                  value={formData.targetValue || ''}
                  onChange={(e) => handleChange('targetValue', parseFloat(e.target.value) || undefined)}
                  placeholder="직접 입력"
                  sx={{ mt: 1 }}
                />
              ) : null}
            </Grid>
          )}

          {/* 보조값 (BETWEEN) */}
          {showSecondaryValue && (
            <Grid item xs={12} sm={6} md={3}>
              <TextField
                fullWidth
                size="small"
                label="상한값"
                type="number"
                value={formData.secondaryValue || ''}
                onChange={(e) => handleChange('secondaryValue', parseFloat(e.target.value) || undefined)}
                helperText="범위의 상한값"
              />
            </Grid>
          )}

          {/* 설명 (선택사항) */}
          <Grid item xs={12}>
            <Accordion>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Typography variant="body2">설명 추가 (선택)</Typography>
              </AccordionSummary>
              <AccordionDetails>
                <TextField
                  fullWidth
                  size="small"
                  multiline
                  rows={3}
                  value={formData.description || ''}
                  onChange={(e) => handleChange('description', e.target.value)}
                  placeholder="조건에 대한 설명을 입력하세요"
                />
              </AccordionDetails>
            </Accordion>
          </Grid>
        </Grid>
      </DialogContent>

      <DialogActions>
        <Button onClick={onCancel}>
          취소
        </Button>
        <Button
          onClick={handleSubmit}
          variant="contained"
          disabled={saving}
        >
          {saving ? '저장 중...' : '저장'}
        </Button>
      </DialogActions>
    </>
  );
};

export default GlobalAlertConditionEditor;
