import React, { useState, useEffect, useMemo } from 'react';
import {
  Box,
  Grid,
  Paper,
  Typography,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Tooltip,
  Chip,
  Switch,
  Divider,
} from '@mui/material';
import {
  Save as SaveIcon,
  VolumeUp as VolumeUpIcon,
  Notifications as NotificationsIcon,
  ShowChart as ShowChartIcon,
} from '@mui/icons-material';
import { getScheduleConfig, saveScheduleConfig, getSchedulerStatus, startScheduler, createTestNotification, AlertScheduleConfigDto } from '../services/alertApi';
import CryptoListPanel from '../components/alert/CryptoListPanel';
import AlertStrategyPanel from '../components/alert/AlertStrategyPanel';
import AlertNotificationList from '../components/alert/AlertNotificationList';
import { useNavigation } from '../contexts/NavigationContext';
import { useAlertNotification } from '../contexts/AlertNotificationContext';
import AlertRealtimeStrategyPopup from '../components/alert/AlertRealtimeStrategyPopup';

/**
 * 알림 페이지 - 통합 레이아웃
 * 좌측: 알림 목록
 * 우측: 알림 설정 (종목 목록 + 전략 설정 + 스케줄 설정)
 */
const AlertPage: React.FC = () => {
  const { navigateToPage } = useNavigation();
  const { loadNotifications } = useAlertNotification();
  const [scheduleConfig, setScheduleConfig] = useState<AlertScheduleConfigDto>({
    cronExpression: '0 */5 * * * ?',
    timeInterval: '1h',
    strategyCheckIntervalSeconds: 5,
    enabled: true,
  });

  const strategyCheckIntervalOptions = useMemo(() => Array.from({ length: 28 }, (_, i) => i + 3), []);
  const [alertSound, setAlertSound] = useState<string>('bell'); // 기본값: bell
  const [schedulerRunning, setSchedulerRunning] = useState<boolean | null>(null);
  const [schedulerLoading, setSchedulerLoading] = useState(false);
  const [schedulerStarting, setSchedulerStarting] = useState(false);
  const [testAlertLoading, setTestAlertLoading] = useState(false);
  const [rtStrategyAnchor, setRtStrategyAnchor] = useState<HTMLElement | null>(null);

  // ✅ 컴포넌트 마운트 시 스케줄 로드, 알람소리 설정 로드, 알림 목록 새로고침
  useEffect(() => {
    loadScheduleConfig();
    loadNotifications(); // 스낵바 팝업용 Context 알림 동기화
    // localStorage에서 알람소리 설정 로드
    const savedSound = localStorage.getItem('alertSound');
    if (savedSound) {
      setAlertSound(savedSound);
    }
  }, []);

  // 스케줄러 상태 주기적 확인
  const loadSchedulerStatus = async () => {
    setSchedulerLoading(true);
    try {
      const status = await getSchedulerStatus();
      setSchedulerRunning(status.running);
    } catch (err) {
      console.error('스케줄러 상태 조회 실패:', err);
      setSchedulerRunning(false);
    } finally {
      setSchedulerLoading(false);
    }
  };

  useEffect(() => {
    loadSchedulerStatus();
    const interval = setInterval(loadSchedulerStatus, 30000); // 30초마다 확인
    return () => clearInterval(interval);
  }, []);

  const handleStartScheduler = async () => {
    setSchedulerStarting(true);
    try {
      const result = await startScheduler();
      if (result.success) {
        alert(result.message);
        await loadSchedulerStatus();
      } else {
        alert(result.message + (result.manualCommand ? `\n\n수동 실행: ${result.manualCommand}` : ''));
      }
    } catch (err: any) {
      alert('스케줄러 시작 요청 실패: ' + (err?.message || err));
    } finally {
      setSchedulerStarting(false);
    }
  };


  const loadScheduleConfig = async () => {
    try {
      const config = await getScheduleConfig();
      setScheduleConfig(config);
    } catch (error) {
      console.error('스케줄 설정 로드 실패:', error);
    }
  };

  const handleTimeIntervalChange = async (event: any) => {
    const timeInterval = event.target.value as string;
    const newConfig = {
      ...scheduleConfig,
      timeInterval,
    };
    setScheduleConfig(newConfig);
    try {
      await saveScheduleConfig(newConfig);
    } catch (error) {
      console.error('평가 시간봉 저장 실패:', error);
      alert('평가 시간봉 저장에 실패했습니다.');
    }
  };

  const handleStrategyCheckIntervalChange = async (event: any) => {
    const strategyCheckIntervalSeconds = Number(event.target.value);
    const newConfig = {
      ...scheduleConfig,
      strategyCheckIntervalSeconds,
    };
    setScheduleConfig(newConfig);
    try {
      await saveScheduleConfig(newConfig);
    } catch (error) {
      console.error('전략 평가 주기 저장 실패:', error);
      alert('전략 평가 주기 저장에 실패했습니다.');
    }
  };

  const handleSaveSchedule = async () => {
    try {
      await saveScheduleConfig(scheduleConfig);
      alert('스케줄 설정이 저장되었습니다.');
    } catch (error) {
      console.error('스케줄 설정 저장 실패:', error);
      alert('스케줄 설정 저장에 실패했습니다.');
    }
  };

  // 알람소리 변경 핸들러
  const handleSoundChange = (event: any) => {
    const sound = event.target.value as string;
    setAlertSound(sound);
    localStorage.setItem('alertSound', sound);
  };

  // 테스트 알림 생성 (파이프라인 검증용)
  const handleTestAlert = async () => {
    setTestAlertLoading(true);
    try {
      await createTestNotification();
      await loadNotifications();  // 즉시 새로고침하여 팝업 표시
      alert('테스트 알림이 생성되었습니다. 팝업이 표시됩니다.');
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.message || '종목을 먼저 추가해주세요.';
      alert('테스트 알림 생성 실패: ' + msg);
    } finally {
      setTestAlertLoading(false);
    }
  };

  // 알람소리 미리듣기
  const playTestSound = () => {
    if (alertSound === 'silent') {
      alert('무음이 선택되었습니다. 알림 발생 시 소리 없이 팝업만 표시됩니다.');
      return;
    }
    const audio = new Audio(getAlertSoundUrl(alertSound));
    audio.play().catch(err => console.error('소리 재생 실패:', err));
  };

  // 알람소리 URL 가져오기
  const getAlertSoundUrl = (soundType: string): string => {
    switch (soundType) {
      case 'silent':
        return ''; // 무음
      case 'bell':
        return 'https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3'; // Bell notification
      case 'chime':
        return 'https://assets.mixkit.co/active_storage/sfx/2870/2870-preview.mp3'; // Chime notification
      case 'alert':
        return 'https://assets.mixkit.co/active_storage/sfx/2868/2868-preview.mp3'; // Alert notification
      case 'success':
        return 'https://assets.mixkit.co/active_storage/sfx/2018/2018-preview.mp3'; // Success notification
      case 'ding':
        return 'https://assets.mixkit.co/active_storage/sfx/2354/2354-preview.mp3'; // Ding notification
      case 'message':
        return 'https://assets.mixkit.co/active_storage/sfx/2357/2357-preview.mp3'; // Message pop
      case 'notification':
        return 'https://assets.mixkit.co/active_storage/sfx/2359/2359-preview.mp3'; // Notification tone
      case 'ring':
        return 'https://assets.mixkit.co/active_storage/sfx/2356/2356-preview.mp3'; // Phone ring
      case 'alert2':
        return 'https://assets.mixkit.co/active_storage/sfx/2358/2358-preview.mp3'; // Alert tone 2
      case 'positive':
        return 'https://assets.mixkit.co/active_storage/sfx/2000/2000-preview.mp3'; // Positive notification
      case 'beep':
        return 'https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3'; // Beep sound
      case 'coin':
        return 'https://assets.mixkit.co/active_storage/sfx/1998/1998-preview.mp3'; // Coin notification
      case 'pop':
        return 'https://assets.mixkit.co/active_storage/sfx/2355/2355-preview.mp3'; // Pop notification
      case 'tone':
        return 'https://assets.mixkit.co/active_storage/sfx/2867/2867-preview.mp3'; // Clean tone
      case 'complete':
        return 'https://assets.mixkit.co/active_storage/sfx/2001/2001-preview.mp3'; // Complete notification
      default:
        return 'https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3';
    }
  };

  // 종목 더블클릭 핸들러 - 분석(투자테스트) 화면으로 이동
  const handleDoubleClickCrypto = (crypto: { symbol: string; koreanName: string; englishName: string }) => {
    console.log('🔔 [AlertPage] 종목 더블클릭:', crypto);
    navigateToPage('candlestick-test', {
      symbol: crypto.symbol,
      koreanName: crypto.koreanName,
      englishName: crypto.englishName,
      timeInterval: '5m',
    });
  };

  // 알림 목록 더블클릭 핸들러 - 분석(투자테스트) 화면으로 이동
  const handleDoubleClickNotification = (notification: any) => {
    if (notification.symbol) {
      console.log('🔔 [AlertPage] 알림 더블클릭:', notification);
      navigateToPage('candlestick-test', {
        symbol: notification.symbol,
        koreanName: notification.koreanName,
        englishName: notification.englishName,
        timeInterval: '5m',
      });
    }
  };

  return (
    <Box
      sx={{
        width: '100%',
        maxWidth: '100%',
        boxSizing: 'border-box',
        display: 'flex',
        flexDirection: 'column',
        /* App.tsx Container(content 영역) 높이에 맞춤 — flex:1 하단 그리드가 남은 세로 공간 사용 */
        height: '100%',
        minHeight: 0,
        mb: 0,
      }}
    >
      {/* 전역 컨트롤 */}
      <Grid container spacing={{ xs: 2, sm: 2, md: 3 }} sx={{ flexShrink: 0, width: '100%' }}>
        <Grid item xs={12}>
          <Paper sx={{ py: 1.25, px: 2 }}>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: { xs: 1.5, sm: 2 },
                  flexWrap: 'wrap',
                  rowGap: 1,
                }}
              >
                {/* 전역 알림 ON/OFF */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, minWidth: { xs: '100%', sm: 'auto' } }}>
                  <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap', fontWeight: 500, fontSize: { xs: '0.9rem', sm: '1rem' } }}>
                    알림 ON/OFF
                  </Typography>
                  <Chip 
                    label={scheduleConfig.enabled ? "ON" : "OFF"}
                    color={scheduleConfig.enabled ? "success" : "default"}
                    size="small"
                  />
                  <Switch
                    checked={scheduleConfig.enabled || false}
                    onChange={(e) => {
                      const newConfig = {
                        ...scheduleConfig,
                        enabled: e.target.checked,
                      };
                      setScheduleConfig(newConfig);
                      saveScheduleConfig(newConfig).catch((error) => {
                        console.error('알림 ON/OFF 저장 실패:', error);
                        alert('알림 설정 저장에 실패했습니다.');
                      });
                    }}
                    color="primary"
                  />
                  {/* 알림서비스 상태 표시 */}
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, ml: 1 }}>
                    <Typography variant="body2" color="text.secondary" sx={{ whiteSpace: 'nowrap' }}>
                      알림서비스 상태:
                    </Typography>
                    {schedulerLoading ? (
                      <Typography variant="body2" color="text.secondary">확인중...</Typography>
                    ) : schedulerRunning === true ? (
                      <Chip label="실행중" color="success" size="small" />
                    ) : (
                      <>
                        <Chip label="미실행" color="default" size="small" />
                        <Button
                          variant="contained"
                          size="small"
                          onClick={handleStartScheduler}
                          disabled={schedulerStarting}
                        >
                          {schedulerStarting ? '시작중...' : '서비스 시작'}
                        </Button>
                      </>
                    )}
                  </Box>
                </Box>

                <Divider orientation="vertical" flexItem sx={{ display: { xs: 'none', sm: 'block' } }} />

                {/* 스케줄 설정: 평가에 쓸 시간봉 + 전략 평가 주기(초) */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap', minWidth: { xs: '100%', sm: 'auto' } }}>
                  <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap', fontWeight: 500, fontSize: { xs: '0.9rem', sm: '1rem' } }}>
                    전략 평가
                  </Typography>
                  <FormControl size="small" sx={{ minWidth: '120px' }}>
                    <InputLabel id="alert-eval-tf-label">평가 시간봉</InputLabel>
                    <Select
                      labelId="alert-eval-tf-label"
                      value={scheduleConfig.timeInterval || '1h'}
                      label="평가 시간봉"
                      onChange={handleTimeIntervalChange}
                    >
                      <MenuItem value="1m">1분봉</MenuItem>
                      <MenuItem value="3m">3분봉</MenuItem>
                      <MenuItem value="5m">5분봉</MenuItem>
                      <MenuItem value="10m">10분봉</MenuItem>
                      <MenuItem value="15m">15분봉</MenuItem>
                      <MenuItem value="30m">30분봉</MenuItem>
                      <MenuItem value="1h">1시간봉</MenuItem>
                      <MenuItem value="4h">4시간봉</MenuItem>
                    </Select>
                  </FormControl>
                  <FormControl size="small" sx={{ minWidth: '100px' }}>
                    <InputLabel id="alert-strategy-interval-label">평가 주기(초)</InputLabel>
                    <Select
                      labelId="alert-strategy-interval-label"
                      value={scheduleConfig.strategyCheckIntervalSeconds ?? 5}
                      label="평가 주기(초)"
                      onChange={handleStrategyCheckIntervalChange}
                    >
                      {strategyCheckIntervalOptions.map((sec) => (
                        <MenuItem key={sec} value={sec}>
                          {sec}초
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Box>

                <Divider orientation="vertical" flexItem sx={{ display: { xs: 'none', sm: 'block' } }} />

                {/* 알람소리 설정 */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, minWidth: { xs: '100%', sm: '180px' }, flex: { sm: 1 }, maxWidth: { sm: '240px' } }}>
                  <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap', fontWeight: 500, fontSize: { xs: '0.9rem', sm: '1rem' } }}>
                    알람소리
                  </Typography>
                  <FormControl size="small" sx={{ flex: 1, minWidth: '100px' }}>
                    <Select
                      value={alertSound}
                      onChange={handleSoundChange}
                      displayEmpty
                    >
                      <MenuItem value="silent">무음</MenuItem>
                      <MenuItem value="bell">벨</MenuItem>
                      <MenuItem value="chime">차임</MenuItem>
                      <MenuItem value="alert">알림</MenuItem>
                      <MenuItem value="success">성공</MenuItem>
                      <MenuItem value="ding">딩</MenuItem>
                      <MenuItem value="message">메시지</MenuItem>
                      <MenuItem value="coin">코인</MenuItem>
                    </Select>
                  </FormControl>
                  <IconButton
                    onClick={playTestSound}
                    color="primary"
                    size="small"
                    title="미리듣기"
                  >
                    <VolumeUpIcon />
                  </IconButton>
                </Box>

                {/* 저장 버튼 */}
                <Button
                  variant="contained"
                  startIcon={<SaveIcon />}
                  onClick={handleSaveSchedule}
                  size="small"
                  sx={{ minWidth: { xs: '100%', sm: 'auto' } }}
                >
                  저장
                </Button>
                {/* 테스트 알림 버튼 (파이프라인 검증용) */}
                <Button
                  variant="outlined"
                  onClick={handleTestAlert}
                  disabled={testAlertLoading}
                  size="small"
                  sx={{ minWidth: { xs: '100%', sm: 'auto' } }}
                >
                  {testAlertLoading ? '생성중...' : '테스트 알림'}
                </Button>
                <Tooltip title="실시간 전략 데이터">
                  <IconButton
                    color="primary"
                    size="small"
                    aria-label="실시간 전략 데이터"
                    onClick={async (e) => {
                      const el = e.currentTarget;
                      try {
                        const c = await getScheduleConfig();
                        setScheduleConfig((prev) => ({
                          ...prev,
                          lastRunTime: c.lastRunTime as typeof prev.lastRunTime,
                          nextRunTime: c.nextRunTime as typeof prev.nextRunTime,
                        }));
                      } catch {
                        /* 스케줄 조회 실패 시 기존 state로 팝업만 열기 */
                      }
                      setRtStrategyAnchor(el);
                    }}
                    sx={{ border: 1, borderColor: 'divider', borderRadius: 1 }}
                  >
                    <ShowChartIcon fontSize="small" />
                  </IconButton>
                </Tooltip>
              </Box>

              {/* 실행 시간 정보 */}
              {scheduleConfig.lastRunTime && (
                <Box sx={{ mt: 1.5, pt: 1.5, borderTop: 1, borderColor: 'divider' }}>
                  <Typography variant="caption" color="text.secondary" display="block">
                    마지막 실행: {new Date(scheduleConfig.lastRunTime).toLocaleString('ko-KR')}
                  </Typography>
                  {scheduleConfig.nextRunTime && (
                    <Typography variant="caption" color="text.secondary" display="block">
                      다음 실행: {new Date(scheduleConfig.nextRunTime).toLocaleString('ko-KR')}
                    </Typography>
                  )}
                </Box>
              )}
            </Paper>
        </Grid>
      </Grid>

      {/* 알림 대상 종목 | 알림 조건 | 알림 목록 — 남은 높이 전부 사용 */}
      <Grid
        container
        spacing={{ xs: 2, sm: 2, md: 3 }}
        sx={{
          flex: 1,
          minHeight: 0,
          width: '100%',
          alignContent: 'stretch',
          mt: 0,
        }}
      >
        <Grid item xs={12} md={6} lg={4} sx={{ display: 'flex', flexDirection: 'column', minHeight: { xs: 360, md: 0 } }}>
          <Paper sx={{ 
            p: 2.5, 
            flex: 1,
            minHeight: 0,
            width: '100%',
            display: 'flex', 
            flexDirection: 'column' 
          }}>
            <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1, fontSize: { xs: '1rem', sm: '1.25rem' } }}>
              📊 알림 대상 종목
            </Typography>
            <Typography variant="caption" color="text.secondary" sx={{ mb: 2, fontSize: { xs: '0.7rem', sm: '0.75rem' } }}>
              알림을 받을 종목을 선택하세요. 활성화된 종목에 대해 알림 조건을 체크합니다.
            </Typography>
            <Divider sx={{ mb: 2 }} />
            <Box sx={{ flexGrow: 1, minHeight: 0, overflow: 'auto' }}>
              <CryptoListPanel
                onSelectCrypto={(crypto, alertId) => {
                  // 종목 선택은 알림 ON/OFF만 담당
                }}
                selectedSymbol={undefined}
                onDoubleClickCrypto={handleDoubleClickCrypto}
              />
            </Box>
          </Paper>
        </Grid>

        <Grid item xs={12} md={6} lg={4} sx={{ display: 'flex', flexDirection: 'column', minHeight: { xs: 360, md: 0 } }}>
          <Paper sx={{ 
            p: 2.5, 
            flex: 1,
            minHeight: 0,
            width: '100%',
            display: 'flex', 
            flexDirection: 'column' 
          }}>
            <Box sx={{ flexGrow: 1, minHeight: 0, overflow: 'auto' }}>
              <AlertStrategyPanel />
            </Box>
          </Paper>
        </Grid>

        <Grid item xs={12} md={12} lg={4} sx={{ display: 'flex', flexDirection: 'column', minHeight: { xs: 360, md: 0 } }}>
          <Paper 
            sx={{ 
              flex: 1,
              minHeight: 0,
              width: '100%',
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden'
            }}
          >
            {/* 알림 목록 헤더 */}
            <Box sx={{ 
              p: 2, 
              borderBottom: 1, 
              borderColor: 'divider',
              display: 'flex',
              alignItems: 'center',
              gap: 1
            }}>
              <NotificationsIcon color="primary" />
              <Typography variant="h6" sx={{ flexGrow: 1, fontSize: { xs: '1rem', sm: '1.25rem' } }}>
                알림 목록
              </Typography>
            </Box>

            {/* 알림 목록 컨텐츠 */}
            <Box sx={{ flexGrow: 1, minHeight: 0, overflow: 'auto' }}>
              <AlertNotificationList 
                maxItems={100}
                onDoubleClickNotification={handleDoubleClickNotification}
              />
            </Box>
          </Paper>
        </Grid>
      </Grid>

      {rtStrategyAnchor ? (
        <AlertRealtimeStrategyPopup
          anchorEl={rtStrategyAnchor}
          onClose={() => setRtStrategyAnchor(null)}
          timeInterval={scheduleConfig.timeInterval || '1h'}
          lastStrategyRunTime={scheduleConfig.lastRunTime}
          nextStrategyRunTime={scheduleConfig.nextRunTime}
        />
      ) : null}
    </Box>
  );
};

export default AlertPage;

