import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  Typography,
} from '@mui/material';
import {
  addCondition,
  updateCondition,
  AlertConditionDto,
  IndicatorType,
  ConditionType,
} from '../../services/alertApi';

interface AlertConditionEditorProps {
  alertId: number;
  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' },
];

// 조건 타입 옵션
const CONDITION_OPTIONS: { value: ConditionType; label: string }[] = [
  { value: 'CROSS_UP', label: '상향 돌파' },
  { value: 'CROSS_DOWN', label: '하향 돌파' },
  { value: 'ABOVE', label: '초과' },
  { value: 'BELOW', label: '미만' },
  { value: 'BETWEEN', label: '범위 내' },
  { value: 'ZERO_CROSS_UP', label: '0선 상향 돌파' },
  { value: 'ZERO_CROSS_DOWN', label: '0선 하향 돌파' },
  { value: 'SIGNAL_CROSS_UP', label: '시그널선 상향 돌파' },
  { value: 'SIGNAL_CROSS_DOWN', label: '시그널선 하향 돌파' },
];

/**
 * 알림 조건 에디터
 */
const AlertConditionEditor: React.FC<AlertConditionEditorProps> = ({
  alertId,
  condition,
  onSave,
  onCancel,
}) => {
  const [formData, setFormData] = useState<AlertConditionDto>({
    indicatorType: 'RSI',
    conditionType: 'ABOVE',
    targetValue: undefined,
    secondaryValue: undefined,
    period: undefined,
    enabled: true,
    orderIndex: 0,
    description: '',
    logicalOperator: 'AND',
  });

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

  useEffect(() => {
    if (condition) {
      setFormData(condition);
    }
  }, [condition]);

  const handleChange = (field: keyof AlertConditionDto, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value,
    }));
  };

  const needsTargetValue = (): boolean => {
    const { conditionType } = formData;
    return ['ABOVE', 'BELOW', 'EQUAL'].includes(conditionType);
  };

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

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

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

  return (
    <>
      <DialogTitle>
        {condition ? '조건 수정' : '조건 추가'}
      </DialogTitle>
      
      <DialogContent>
        <Grid container spacing={2} sx={{ mt: 1 }}>
          {/* 지표 선택 */}
          <Grid item xs={12} sm={6}>
            <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>

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

          {/* 기준값 */}
          {needsTargetValue() && (
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                size="small"
                label="기준값"
                type="number"
                value={formData.targetValue || ''}
                onChange={(e) => handleChange('targetValue', parseFloat(e.target.value) || undefined)}
                helperText="예: RSI 30, 70"
              />
            </Grid>
          )}

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

          {/* 기간 */}
          {needsPeriod() && (
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                size="small"
                label="기간"
                type="number"
                value={formData.period || ''}
                onChange={(e) => handleChange('period', parseInt(e.target.value) || undefined)}
                helperText="예: RSI 14, Stochastic 12"
              />
            </Grid>
          )}

          {/* 설명 */}
          <Grid item xs={12}>
            <TextField
              fullWidth
              size="small"
              label="설명 (선택)"
              multiline
              rows={2}
              value={formData.description || ''}
              onChange={(e) => handleChange('description', e.target.value)}
              placeholder="조건에 대한 설명을 입력하세요"
            />
          </Grid>

          {/* 논리 연산자 */}
          <Grid item xs={12}>
            <FormControl fullWidth size="small">
              <InputLabel>다음 조건과의 관계</InputLabel>
              <Select
                value={formData.logicalOperator || 'AND'}
                label="다음 조건과의 관계"
                onChange={(e) => handleChange('logicalOperator', e.target.value)}
              >
                <MenuItem value="AND">AND (그리고)</MenuItem>
                <MenuItem value="OR">OR (또는)</MenuItem>
              </Select>
            </FormControl>
            <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5, display: 'block' }}>
              여러 조건이 있을 때 조건들 간의 관계를 설정합니다.
            </Typography>
          </Grid>
        </Grid>
      </DialogContent>

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

export default AlertConditionEditor;

