import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  Grid,
  Button,
  Card,
  CardContent,
  CircularProgress,
  Alert,
  Chip,
  LinearProgress,
  TextField,
  Switch,
  FormControlLabel,
  Divider,
} from '@mui/material';
import {
  Schedule,
  PlayArrow,
  Stop,
  Refresh,
  CheckCircle,
  AccessTime,
  CloudDownload,
  Settings,
} from '@mui/icons-material';
import { schedulerApi, SchedulerStatus } from '../services/schedulerApi';
import { settingsApi } from '../services/settingsApi';

const SchedulerPage: React.FC = () => {
  const [status, setStatus] = useState<SchedulerStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  // 설정 상태
  const [enabled, setEnabled] = useState(true);
  const [cronExpression, setCronExpression] = useState('0 0 6 * * ?');
  const [downloadDir, setDownloadDir] = useState('/Users/macbook/dev/upbit/upbit_candle_data');
  const [maxWorkers, setMaxWorkers] = useState(15);

  const loadStatus = useCallback(async () => {
    try {
      setError(null);
      const data = await schedulerApi.getStatus();
      setStatus(data);
      setEnabled(data.isEnabled);
      setCronExpression(data.cronExpression);
      setDownloadDir(data.downloadDir);
      setMaxWorkers(data.maxWorkers);
    } catch (err: any) {
      console.error('스케쥴러 상태 로드 실패:', err);
      setError('스케쥴러 상태를 불러오는데 실패했습니다.');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadStatus();
    // 실행 중인 경우 자동 새로고침
    const interval = setInterval(() => {
      if (status?.isRunning) {
        loadStatus();
      }
    }, 2000);
    return () => clearInterval(interval);
  }, [loadStatus, status?.isRunning]);

  const handleStartDownload = async () => {
    try {
      setError(null);
      const result = await schedulerApi.startDownload();
      setStatus(result);
    } catch (err: any) {
      setError('다운로드 시작 실패: ' + err.message);
    }
  };

  const handleStopDownload = async () => {
    try {
      const result = await schedulerApi.stopDownload();
      setStatus(result);
    } catch (err: any) {
      setError('다운로드 중단 실패: ' + err.message);
    }
  };

  const handleSaveSettings = async () => {
    try {
      setSaving(true);
      setError(null);
      
      await settingsApi.saveSettings([
        { key: 'scheduler_enabled', value: String(enabled), type: 'BOOLEAN', category: 'SCHEDULER' },
        { key: 'scheduler_cron', value: cronExpression, type: 'STRING', category: 'SCHEDULER' },
        { key: 'scheduler_download_dir', value: downloadDir, type: 'STRING', category: 'SCHEDULER' },
        { key: 'scheduler_max_workers', value: String(maxWorkers), type: 'NUMBER', category: 'SCHEDULER' },
      ]);

      await loadStatus();
    } catch (err: any) {
      setError('설정 저장 실패: ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box className="fade-in">
      <Typography variant="h4" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Schedule color="primary" />
        스케쥴러
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
        매일 지정된 시간에 자동으로 업비트 캔들 데이터를 다운로드합니다.
      </Typography>

      {error && <Alert severity="error" sx={{ mb: 3 }}>{error}</Alert>}

      {/* 실행 상태 */}
      {status?.isRunning && (
        <Paper elevation={0} sx={{ p: 3, mb: 3, bgcolor: 'background.paper', border: '1px solid rgba(100, 149, 237, 0.3)' }}>
          <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <CircularProgress size={20} />
            다운로드 진행 중...
          </Typography>
          <Box sx={{ mb: 2 }}>
            <LinearProgress 
              variant="determinate" 
              value={status.progressPercent} 
              sx={{ height: 10, borderRadius: 5 }}
            />
            <Typography variant="body2" sx={{ mt: 1 }}>
              진행률: {status.progressPercent.toFixed(1)}%
            </Typography>
          </Box>
          <Typography variant="body2" color="text.secondary">
            {status.currentTask}
          </Typography>
          <Box sx={{ display: 'flex', gap: 2, mt: 2 }}>
            <Chip label={`다운로드: ${status.downloadedFilesCount}`} color="success" />
            <Chip label={`실패: ${status.failedFilesCount}`} color="error" />
          </Box>
        </Paper>
      )}

      <Grid container spacing={3}>
        {/* 현재 상태 */}
        <Grid item xs={12} md={6}>
          <Paper elevation={0} sx={{ p: 3, bgcolor: 'background.paper', border: '1px solid rgba(100, 149, 237, 0.2)', height: '100%' }}>
            <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <AccessTime />
              스케쥴러 상태
            </Typography>
            
            <Grid container spacing={2} sx={{ mb: 3 }}>
              <Grid item xs={6}>
                <Card variant="outlined" sx={{ bgcolor: 'transparent' }}>
                  <CardContent>
                    <Typography variant="body2" color="text.secondary">활성화 상태</Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
                      {status?.isEnabled ? (
                        <>
                          <CheckCircle color="success" />
                          <Typography color="success.main">활성화</Typography>
                        </>
                      ) : (
                        <Typography color="text.secondary">비활성화</Typography>
                      )}
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={6}>
                <Card variant="outlined" sx={{ bgcolor: 'transparent' }}>
                  <CardContent>
                    <Typography variant="body2" color="text.secondary">실행 상태</Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
                      {status?.isRunning ? (
                        <>
                          <CircularProgress size={16} />
                          <Typography color="primary.main">실행 중</Typography>
                        </>
                      ) : (
                        <Typography color="text.secondary">대기 중</Typography>
                      )}
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>

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

            <Box sx={{ mb: 2 }}>
              <Typography variant="body2" color="text.secondary">다음 실행 예정</Typography>
              <Typography variant="h6">
                {status?.nextRunTime ? new Date(status.nextRunTime).toLocaleString('ko-KR') : '-'}
              </Typography>
            </Box>

            <Box sx={{ mb: 2 }}>
              <Typography variant="body2" color="text.secondary">마지막 실행</Typography>
              <Typography variant="body1">
                {status?.lastRunTime ? new Date(status.lastRunTime).toLocaleString('ko-KR') : '-'}
              </Typography>
              {status?.lastRunResult && (
                <Typography variant="body2" color="text.secondary">
                  결과: {status.lastRunResult}
                </Typography>
              )}
            </Box>

            <Box sx={{ display: 'flex', gap: 2 }}>
              {status?.isRunning ? (
                <Button
                  variant="contained"
                  color="error"
                  startIcon={<Stop />}
                  onClick={handleStopDownload}
                  fullWidth
                >
                  중단
                </Button>
              ) : (
                <Button
                  variant="contained"
                  color="primary"
                  startIcon={<PlayArrow />}
                  onClick={handleStartDownload}
                  fullWidth
                >
                  수동 실행
                </Button>
              )}
              <Button
                variant="outlined"
                startIcon={<Refresh />}
                onClick={loadStatus}
                disabled={status?.isRunning}
              >
                새로고침
              </Button>
            </Box>
          </Paper>
        </Grid>

        {/* 스케쥴러 설정 */}
        <Grid item xs={12} md={6}>
          <Paper elevation={0} sx={{ p: 3, bgcolor: 'background.paper', border: '1px solid rgba(100, 149, 237, 0.2)', height: '100%' }}>
            <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Settings />
              스케쥴러 설정
            </Typography>

            <Box sx={{ mb: 3 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={enabled}
                    onChange={(e) => setEnabled(e.target.checked)}
                    disabled={status?.isRunning}
                  />
                }
                label="스케쥴러 활성화"
              />
            </Box>

            <TextField
              fullWidth
              label="크론 표현식"
              value={cronExpression}
              onChange={(e) => setCronExpression(e.target.value)}
              disabled={status?.isRunning}
              helperText="예: 0 0 6 * * ? (매일 오전 6시)"
              sx={{ mb: 2 }}
            />

            <TextField
              fullWidth
              label="다운로드 경로"
              value={downloadDir}
              onChange={(e) => setDownloadDir(e.target.value)}
              disabled={status?.isRunning}
              sx={{ mb: 2 }}
            />

            <TextField
              fullWidth
              label="동시 다운로드 스레드 수"
              type="number"
              value={maxWorkers}
              onChange={(e) => setMaxWorkers(Number(e.target.value))}
              disabled={status?.isRunning}
              helperText="권장: 10~20"
              sx={{ mb: 3 }}
            />

            <Button
              variant="contained"
              color="primary"
              onClick={handleSaveSettings}
              disabled={status?.isRunning || saving}
              fullWidth
              startIcon={saving ? <CircularProgress size={16} /> : null}
            >
              {saving ? '저장 중...' : '설정 저장'}
            </Button>
          </Paper>
        </Grid>
      </Grid>

      {/* 다운로드 정보 */}
      <Paper elevation={0} sx={{ p: 3, mt: 3, bgcolor: 'background.paper', border: '1px solid rgba(100, 149, 237, 0.2)' }}>
        <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <CloudDownload />
          다운로드 정보
        </Typography>
        <Alert severity="info" sx={{ mb: 2 }}>
          업비트 Historical Data API를 통해 캔들 데이터 ZIP 파일을 다운로드합니다.
        </Alert>
        <Grid container spacing={2}>
          <Grid item xs={12} md={4}>
            <Typography variant="body2" color="text.secondary">다운로드 URL</Typography>
            <Typography variant="body2" sx={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
              https://crix-data.upbit.com/candle/&#123;MARKET&#125;/daily/&#123;TIME_UNIT&#125;/&#123;YEAR&#125;/&#123;FILENAME&#125;
            </Typography>
          </Grid>
          <Grid item xs={12} md={4}>
            <Typography variant="body2" color="text.secondary">시간단위</Typography>
            <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mt: 0.5 }}>
              {['1m', '3m', '5m', '15m', '30m', '60m', '240m', '1d', '1w', '1M'].map(unit => (
                <Chip key={unit} label={unit} size="small" variant="outlined" />
              ))}
            </Box>
          </Grid>
          <Grid item xs={12} md={4}>
            <Typography variant="body2" color="text.secondary">저장 구조</Typography>
            <Typography variant="body2" sx={{ fontFamily: 'monospace' }}>
              &#123;MARKET&#125;/&#123;TIME_UNIT&#125;/&#123;YEAR&#125;/*.zip
            </Typography>
          </Grid>
        </Grid>
      </Paper>
    </Box>
  );
};

export default SchedulerPage;

