import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  Typography,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Grid,
  Alert,
  Button,
  Divider,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { RestartAlt } from '@mui/icons-material';
import {
  SignalWeightSettings,
  getSignalWeights,
  saveSignalWeights,
  resetSignalWeights,
  getDefaultWeights,
} from '../../services/signalWeightApi';

const SignalWeightSettingsTab: React.FC = () => {
  const [weights, setWeights] = useState<SignalWeightSettings>(getDefaultWeights());
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const loadSettings = async () => {
    try {
      const loadedWeights = await getSignalWeights();
      setWeights(loadedWeights);
    } catch (err) {
      console.error('설정 로드 실패:', err);
      setError('설정을 불러오는데 실패했습니다.');
    }
  };

  const handleSave = async () => {
    try {
      setError(null);
      await saveSignalWeights(weights);
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err) {
      console.error('설정 저장 실패:', err);
      setError('설정 저장에 실패했습니다.');
    }
  };

  const handleReset = async () => {
    if (window.confirm('모든 설정을 기본값으로 초기화하시겠습니까?')) {
      try {
        setError(null);
        await resetSignalWeights();
        const defaultWeights = getDefaultWeights();
        setWeights(defaultWeights);
        setSuccess(true);
        setTimeout(() => setSuccess(false), 3000);
      } catch (err) {
        console.error('설정 초기화 실패:', err);
        setError('설정 초기화에 실패했습니다.');
      }
    }
  };

  const handleChange = (field: keyof SignalWeightSettings, value: number) => {
    setWeights(prev => ({ ...prev, [field]: value }));
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">
          매매 신호 가중치 설정
        </Typography>
        <Button
          variant="outlined"
          size="small"
          startIcon={<RestartAlt />}
          onClick={handleReset}
          color="secondary"
        >
          초기화
        </Button>
      </Box>

      {success && (
        <Alert severity="success" sx={{ mb: 2 }}>
          설정이 저장되었습니다.
        </Alert>
      )}

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

      <Alert severity="info" sx={{ mb: 3 }}>
        <Typography variant="body2">
          각 지표별 매매 신호의 가중치를 조정하여 종합 점수를 계산합니다.
        </Typography>
      </Alert>

      {/* MACD */}
      <Accordion defaultExpanded>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            📈 MACD
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="골든크로스"
                type="number"
                value={weights.macdGoldenCross}
                onChange={(e) => handleChange('macdGoldenCross', Number(e.target.value))}
                helperText="MACD가 Signal을 상향 돌파"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="데드크로스"
                type="number"
                value={weights.macdDeadCross}
                onChange={(e) => handleChange('macdDeadCross', Number(e.target.value))}
                helperText="MACD가 Signal을 하향 돌파"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="히스토그램 상승 전환"
                type="number"
                value={weights.macdHistogramUp}
                onChange={(e) => handleChange('macdHistogramUp', Number(e.target.value))}
                helperText="히스토그램이 음수→양수"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="히스토그램 하락 전환"
                type="number"
                value={weights.macdHistogramDown}
                onChange={(e) => handleChange('macdHistogramDown', Number(e.target.value))}
                helperText="히스토그램이 양수→음수"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="제로라인 상향 돌파"
                type="number"
                value={weights.macdZeroCrossUp}
                onChange={(e) => handleChange('macdZeroCrossUp', Number(e.target.value))}
                helperText="MACD가 0선 상향 돌파"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="제로라인 하향 돌파"
                type="number"
                value={weights.macdZeroCrossDown}
                onChange={(e) => handleChange('macdZeroCrossDown', Number(e.target.value))}
                helperText="MACD가 0선 하향 돌파"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

      {/* Stochastic Slow */}
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            📊 Stochastic Slow
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="과매도 구간 상향 돌파"
                type="number"
                value={weights.stochOversoldCrossUp}
                onChange={(e) => handleChange('stochOversoldCrossUp', Number(e.target.value))}
                helperText="%K가 %D를 상향 돌파 (과매도)"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="과매수 구간 하향 돌파"
                type="number"
                value={weights.stochOverboughtCrossDown}
                onChange={(e) => handleChange('stochOverboughtCrossDown', Number(e.target.value))}
                helperText="%K가 %D를 하향 돌파 (과매수)"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="과매도 기준값"
                type="number"
                value={weights.stochOversoldThreshold}
                onChange={(e) => handleChange('stochOversoldThreshold', Number(e.target.value))}
                helperText="기본값: 20"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="과매수 기준값"
                type="number"
                value={weights.stochOverboughtThreshold}
                onChange={(e) => handleChange('stochOverboughtThreshold', Number(e.target.value))}
                helperText="기본값: 80"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

      {/* ADX */}
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            📉 ADX
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="강한 상승 추세"
                type="number"
                value={weights.adxStrongUptrend}
                onChange={(e) => handleChange('adxStrongUptrend', Number(e.target.value))}
                helperText="ADX > 기준값 & +DI > -DI"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="강한 하락 추세"
                type="number"
                value={weights.adxStrongDowntrend}
                onChange={(e) => handleChange('adxStrongDowntrend', Number(e.target.value))}
                helperText="ADX > 기준값 & -DI > +DI"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="추세 강도 기준값"
                type="number"
                value={weights.adxThreshold}
                onChange={(e) => handleChange('adxThreshold', Number(e.target.value))}
                helperText="기본값: 25"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

      {/* ADX11 */}
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            📉 ADX11
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="강한 상승 추세 (ADX11)"
                type="number"
                value={weights.adx11StrongUptrend}
                onChange={(e) => handleChange('adx11StrongUptrend', Number(e.target.value))}
                helperText="ADX11 > 기준값 & +DI > -DI"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="강한 하락 추세 (ADX11)"
                type="number"
                value={weights.adx11StrongDowntrend}
                onChange={(e) => handleChange('adx11StrongDowntrend', Number(e.target.value))}
                helperText="ADX11 > 기준값 & -DI > +DI"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="추세 강도 기준값 (ADX11)"
                type="number"
                value={weights.adx11Threshold}
                onChange={(e) => handleChange('adx11Threshold', Number(e.target.value))}
                helperText="기본값: 25"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

      {/* CCI13 */}
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            📊 CCI13
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="강한 상승 모멘텀"
                type="number"
                value={weights.cci13StrongUp}
                onChange={(e) => handleChange('cci13StrongUp', Number(e.target.value))}
                helperText="CCI13 > 과매수 기준값"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="강한 하락 모멘텀"
                type="number"
                value={weights.cci13StrongDown}
                onChange={(e) => handleChange('cci13StrongDown', Number(e.target.value))}
                helperText="CCI13 < 과매도 기준값"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="과매수 기준값"
                type="number"
                value={weights.cci13OverboughtThreshold}
                onChange={(e) => handleChange('cci13OverboughtThreshold', Number(e.target.value))}
                helperText="기본값: 100"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="과매도 기준값"
                type="number"
                value={weights.cci13OversoldThreshold}
                onChange={(e) => handleChange('cci13OversoldThreshold', Number(e.target.value))}
                helperText="기본값: -100"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

      {/* 거래량 */}
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            📊 거래량
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="거래량 급증"
                type="number"
                value={weights.volumeIncrease}
                onChange={(e) => handleChange('volumeIncrease', Number(e.target.value))}
                helperText="거래량 증가율 > 기준값"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="거래량 급감"
                type="number"
                value={weights.volumeDecrease}
                onChange={(e) => handleChange('volumeDecrease', Number(e.target.value))}
                helperText="거래량 감소율 < 기준값"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="거래량 증가율 기준 (%)"
                type="number"
                value={weights.volumeIncreaseThreshold}
                onChange={(e) => handleChange('volumeIncreaseThreshold', Number(e.target.value))}
                helperText="기본값: 30%"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="거래량 감소율 기준 (%)"
                type="number"
                value={weights.volumeDecreaseThreshold}
                onChange={(e) => handleChange('volumeDecreaseThreshold', Number(e.target.value))}
                helperText="기본값: -30%"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

      {/* 종합 신호 기준 */}
      <Accordion>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight="bold">
            🎯 종합 신호 기준
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="매수 신호 기준 점수"
                type="number"
                value={weights.buySignalThreshold}
                onChange={(e) => handleChange('buySignalThreshold', Number(e.target.value))}
                helperText="종합 점수가 이 값보다 크면 매수"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="매도 신호 기준 점수"
                type="number"
                value={weights.sellSignalThreshold}
                onChange={(e) => handleChange('sellSignalThreshold', Number(e.target.value))}
                helperText="종합 점수가 이 값보다 작으면 매도"
              />
            </Grid>
          </Grid>
        </AccordionDetails>
      </Accordion>

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

      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
        <Button variant="contained" onClick={handleSave}>
          저장
        </Button>
      </Box>
    </Box>
  );
};

export default SignalWeightSettingsTab;

