import React, { useState, useEffect, useMemo } from 'react';
import {
  Box,
  Grid,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Alert,
  Chip,
  LinearProgress,
  Tabs,
  Tab,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Tooltip,
  Paper,
  Divider,
  TextField,
  InputAdornment,
} from '@mui/material';
import {
  TrendingUp,
  Storage,
  ShowChart,
  AccessTime,
  EmojiEvents,
  ExpandMore,
  CalendarMonth,
  DataUsage,
  Timeline,
  PlayCircle,
  Schedule,
  CheckCircle,
  Error as ErrorIcon,
  Pending,
  Hub,
  CloudSync,
  Search,
  TableChart,
  Laptop,
} from '@mui/icons-material';
import { 
  dashboardApi, 
  DashboardSummary, 
  StrategyStats, 
  MarketDataStatus,
  StrategyPerformance 
} from '../services/dashboardApi';
import { schedulerApi, SchedulerStatus } from '../services/schedulerApi';
import { getStrategies, TradingStrategy } from '../services/tradingStrategyApi';
import { upbitDbStatusApi, UpbitDbStatus } from '../services/upbitDbStatusApi';
import DashboardDbExplorerTab from '../components/dashboard/DashboardDbExplorerTab';
import SystemMonitorTab from '../components/dashboard/SystemMonitorTab';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`dashboard-tabpanel-${index}`}
      aria-labelledby={`dashboard-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
    </div>
  );
}

const DashboardPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [marketDataStatus, setMarketDataStatus] = useState<MarketDataStatus[]>([]);
  const [schedulerStatus, setSchedulerStatus] = useState<SchedulerStatus | null>(null);
  const [strategies, setStrategies] = useState<TradingStrategy[]>([]);
  const [activeTab, setActiveTab] = useState(0);
  const [upbitDb, setUpbitDb] = useState<UpbitDbStatus | null>(null);
  const [upbitDbLoading, setUpbitDbLoading] = useState(false);
  const [upbitDbRefreshing, setUpbitDbRefreshing] = useState(false);
  const [upbitLastRefreshedAt, setUpbitLastRefreshedAt] = useState<Date | null>(null);
  const [upbitDbError, setUpbitDbError] = useState<string | null>(null);
  const [upbitSeriesFilter, setUpbitSeriesFilter] = useState('');

  /** 백엔드 DB 반영 — 업비트 DB 탭이 보일 때 주기 갱신 */
  const UPBIT_DB_POLL_MS = 5000;

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

  useEffect(() => {
    if (activeTab !== 4) return;
    let cancelled = false;
    const fetchUpbitStatus = async (isInitial: boolean) => {
      if (isInitial) {
        setUpbitDbError(null);
        setUpbitDbLoading(true);
        setUpbitDbRefreshing(false);
      } else {
        setUpbitDbRefreshing(true);
      }
      try {
        const d = await upbitDbStatusApi.getStatus();
        if (cancelled) return;
        setUpbitDb(d);
        setUpbitDbError(null);
        setUpbitLastRefreshedAt(new Date());
      } catch (e: any) {
        if (cancelled) return;
        console.error('업비트 DB 현황 로드 실패:', e);
        const msg = e?.response?.data?.message || e?.message || '로드 실패';
        setUpbitDbError(msg);
        if (isInitial) setUpbitDb(null);
      } finally {
        if (!cancelled) {
          setUpbitDbLoading(false);
          setUpbitDbRefreshing(false);
        }
      }
    };
    void fetchUpbitStatus(true);
    const id = window.setInterval(() => {
      if (document.visibilityState !== 'visible') return;
      void fetchUpbitStatus(false);
    }, UPBIT_DB_POLL_MS);
    return () => {
      cancelled = true;
      window.clearInterval(id);
    };
  }, [activeTab]);

  const filteredUpbitSeries = useMemo(() => {
    if (!upbitDb?.series?.length) return [];
    const q = upbitSeriesFilter.trim().toLowerCase();
    if (!q) return upbitDb.series;
    return upbitDb.series.filter(
      (s) =>
        s.market.toLowerCase().includes(q) ||
        s.timeFrameLabel.toLowerCase().includes(q) ||
        (s.candleType && s.candleType.toLowerCase().includes(q))
    );
  }, [upbitDb, upbitSeriesFilter]);

  const loadDashboard = async () => {
    try {
      setLoading(true);
      setError(null);
      const [summaryData, dataStatus, scheduler, strategiesData] = await Promise.all([
        dashboardApi.getSummary(),
        dashboardApi.getMarketDataStatus(),
        schedulerApi.getStatus().catch(() => null),
        getStrategies().catch(() => []),
      ]);
      setSummary(summaryData);
      setMarketDataStatus(dataStatus);
      setSchedulerStatus(scheduler);
      setStrategies(strategiesData);
    } catch (err: any) {
      console.error('대시보드 로드 실패:', err);
      setError('대시보드 데이터를 불러오는데 실패했습니다. 백엔드 서버를 확인해주세요.');
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString('ko-KR');
  };

  const formatDateTime = (dateStr: string | null) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString('ko-KR');
  };

  const formatNumber = (num: number) => {
    if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
    return num.toString();
  };

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

  if (error) {
    return (
      <Alert severity="error" sx={{ m: 2 }}>
        {error}
      </Alert>
    );
  }

  const StatCard = ({ title, value, icon, color, subtitle }: any) => (
    <Card sx={{ height: '100%' }}>
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <Box>
            <Typography color="text.secondary" variant="body2" gutterBottom>
              {title}
            </Typography>
            <Typography variant="h4" sx={{ color, fontWeight: 700 }}>
              {value}
            </Typography>
            {subtitle && (
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                {subtitle}
              </Typography>
            )}
          </Box>
          <Box sx={{ 
            p: 1.5, 
            borderRadius: 2, 
            bgcolor: `${color}15`,
            color: color 
          }}>
            {icon}
          </Box>
        </Box>
      </CardContent>
    </Card>
  );

  // 데이터 현황 탭
  const DataStatusTab = () => (
    <Box>
      {/* 통계 카드 */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="총 마켓"
            value={summary?.totalMarkets || 0}
            icon={<Storage />}
            color="#6495ed"
            subtitle="수집된 마켓 수"
          />
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="캔들 데이터"
            value={(summary?.totalCandleRecords || 0).toLocaleString()}
            icon={<ShowChart />}
            color="#4ade80"
            subtitle="총 레코드 수"
          />
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="처리된 파일"
            value={(summary?.totalProcessedFiles || 0).toLocaleString()}
            icon={<Storage />}
            color="#fbbf24"
            subtitle="ZIP 파일 수"
          />
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="시간단위"
            value={summary?.totalTimeUnits || 0}
            icon={<AccessTime />}
            color="#f87171"
            subtitle="1m, 1d, 1w 등"
          />
        </Grid>
      </Grid>

      {/* 종목별 데이터 저장 현황 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <DataUsage color="info" />
        종목별 데이터 저장 현황
      </Typography>
      <Card sx={{ mb: 4 }}>
        <CardContent>
          {marketDataStatus.length > 0 ? (
            marketDataStatus.map((market) => (
              <Accordion key={market.market} sx={{ mb: 1 }}>
                <AccordionSummary expandIcon={<ExpandMore />}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, width: '100%', flexWrap: 'wrap' }}>
                    <Typography fontWeight={600} sx={{ minWidth: 120 }}>
                      {market.market}
                    </Typography>
                    <Chip 
                      label={`${formatNumber(market.totalRecords)} 레코드`} 
                      size="small" 
                      color="primary" 
                      variant="outlined" 
                    />
                    <Chip 
                      label={`${market.totalFiles} 파일`} 
                      size="small" 
                      variant="outlined" 
                    />
                    <Chip 
                      label={`${Object.keys(market.timeUnitStatus || {}).length}개 시간봉`} 
                      size="small" 
                      color="info" 
                      variant="outlined" 
                    />
                    {market.oldestDate && market.newestDate && (
                      <Tooltip title="데이터 기간">
                        <Chip
                          icon={<CalendarMonth />}
                          label={`${formatDate(market.oldestDate)} ~ ${formatDate(market.newestDate)}`}
                          size="small"
                          variant="outlined"
                        />
                      </Tooltip>
                    )}
                  </Box>
                </AccordionSummary>
                <AccordionDetails>
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>시간봉</TableCell>
                          <TableCell align="right">레코드 수</TableCell>
                          <TableCell align="right">파일 수</TableCell>
                          <TableCell>시작일</TableCell>
                          <TableCell>종료일</TableCell>
                          <TableCell align="right">기간(일)</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {Object.entries(market.timeUnitStatus || {}).map(([timeUnit, status]) => (
                          <TableRow key={timeUnit} hover>
                            <TableCell>
                              <Chip label={timeUnit} size="small" />
                            </TableCell>
                            <TableCell align="right">
                              {status.recordCount.toLocaleString()}
                            </TableCell>
                            <TableCell align="right">{status.fileCount}</TableCell>
                            <TableCell>{formatDate(status.minDate)}</TableCell>
                            <TableCell>{formatDate(status.maxDate)}</TableCell>
                            <TableCell align="right">
                              {status.daysCovered > 0 ? `${status.daysCovered}일` : '-'}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </AccordionDetails>
              </Accordion>
            ))
          ) : (
            <Typography color="text.secondary" align="center" sx={{ py: 4 }}>
              수집된 데이터가 없습니다. 데이터 수집 탭에서 데이터를 수집해주세요.
            </Typography>
          )}
        </CardContent>
      </Card>

      {/* 데이터 수집 현황 요약 */}
      <Typography variant="h6" sx={{ mb: 2 }}>
        데이터 수집 처리 현황
      </Typography>
      <Card>
        <CardContent>
          {summary?.dataCollectionSummary ? (
            <Grid container spacing={3}>
              <Grid item xs={12} md={4}>
                <Typography variant="body2" color="text.secondary">처리 결과</Typography>
                <Box sx={{ display: 'flex', gap: 1, mt: 1 }}>
                  <Chip label={`성공 ${summary.dataCollectionSummary.successCount}`} color="success" size="small" />
                  <Chip label={`실패 ${summary.dataCollectionSummary.failCount}`} color="error" size="small" />
                  <Chip label={`건너뜀 ${summary.dataCollectionSummary.skipCount}`} variant="outlined" size="small" />
                </Box>
              </Grid>
              <Grid item xs={12} md={4}>
                <Typography variant="body2" color="text.secondary">총 레코드</Typography>
                <Typography variant="h5" sx={{ mt: 0.5 }}>
                  {(summary.dataCollectionSummary.totalRecords || 0).toLocaleString()}
                </Typography>
              </Grid>
              <Grid item xs={12} md={4}>
                <Typography variant="body2" color="text.secondary">처리 파일</Typography>
                <Typography variant="h5" sx={{ mt: 0.5 }}>
                  {(summary.dataCollectionSummary.totalProcessedFiles || 0).toLocaleString()}
                </Typography>
              </Grid>
            </Grid>
          ) : (
            <Typography color="text.secondary" align="center" sx={{ py: 2 }}>
              데이터 수집 탭에서 데이터를 수집해주세요.
            </Typography>
          )}
        </CardContent>
      </Card>
    </Box>
  );

  // 투자전략 현황 탭
  const StrategyStatusTab = () => (
    <Box>
      {/* 최고 성과 전략 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <EmojiEvents color="warning" />
        최고 성과 전략
      </Typography>
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} md={4}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
                <TrendingUp color="success" />
                <Typography variant="h6">최고 수익률</Typography>
              </Box>
              {summary?.topReturnStrategy ? (
                <Box>
                  <Typography variant="body1" fontWeight={600}>
                    {summary.topReturnStrategy.strategyName}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                    {summary.topReturnStrategy.market} / {summary.topReturnStrategy.timeUnit}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 2 }}>
                    <Chip
                      label={`수익률 ${summary.topReturnStrategy.returnRate?.toFixed(2)}%`}
                      size="small"
                      color={summary.topReturnStrategy.returnRate >= 0 ? 'success' : 'error'}
                    />
                    <Chip
                      label={`승률 ${summary.topReturnStrategy.winRate?.toFixed(1)}%`}
                      size="small"
                      variant="outlined"
                    />
                  </Box>
                </Box>
              ) : (
                <Typography color="text.secondary">데이터 없음</Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={4}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
                <TrendingUp color="info" />
                <Typography variant="h6">최고 승률</Typography>
              </Box>
              {summary?.topWinRateStrategy ? (
                <Box>
                  <Typography variant="body1" fontWeight={600}>
                    {summary.topWinRateStrategy.strategyName}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                    {summary.topWinRateStrategy.market} / {summary.topWinRateStrategy.timeUnit}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 2 }}>
                    <Chip
                      label={`승률 ${summary.topWinRateStrategy.winRate?.toFixed(1)}%`}
                      size="small"
                      color="success"
                    />
                    <Chip
                      label={`수익률 ${summary.topWinRateStrategy.returnRate?.toFixed(2)}%`}
                      size="small"
                      variant="outlined"
                    />
                  </Box>
                </Box>
              ) : (
                <Typography color="text.secondary">데이터 없음</Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={4}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
                <TrendingUp color="warning" />
                <Typography variant="h6">최고 샤프비율</Typography>
              </Box>
              {summary?.topSharpeStrategy ? (
                <Box>
                  <Typography variant="body1" fontWeight={600}>
                    {summary.topSharpeStrategy.strategyName}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                    {summary.topSharpeStrategy.market} / {summary.topSharpeStrategy.timeUnit}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 2 }}>
                    <Chip
                      label={`샤프 ${summary.topSharpeStrategy.sharpeRatio?.toFixed(4)}`}
                      size="small"
                      color="warning"
                    />
                    <Chip
                      label={`MDD ${summary.topSharpeStrategy.maxDrawdown?.toFixed(2)}%`}
                      size="small"
                      variant="outlined"
                    />
                  </Box>
                </Box>
              ) : (
                <Typography color="text.secondary">데이터 없음</Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 전략별 통계 테이블 */}
      <Typography variant="h6" sx={{ mb: 2 }}>
        전략별 성과 요약
      </Typography>
      <Card>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>전략명</TableCell>
                <TableCell>유형</TableCell>
                <TableCell align="right">분석 횟수</TableCell>
                <TableCell align="right">평균 수익률</TableCell>
                <TableCell align="right">평균 승률</TableCell>
                <TableCell align="right">평균 MDD</TableCell>
                <TableCell align="right">평균 샤프비율</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {summary?.strategyStats && summary.strategyStats.length > 0 ? (
                summary.strategyStats.map((stat: StrategyStats) => (
                  <TableRow key={stat.strategyId} hover>
                    <TableCell>{stat.strategyName}</TableCell>
                    <TableCell>
                      <Chip label={stat.strategyType} size="small" variant="outlined" />
                    </TableCell>
                    <TableCell align="right">{stat.analysisCount}</TableCell>
                    <TableCell align="right">
                      <Typography
                        sx={{ 
                          color: stat.avgReturnRate >= 0 ? 'success.main' : 'error.main',
                          fontWeight: 600 
                        }}
                      >
                        {stat.avgReturnRate?.toFixed(2)}%
                      </Typography>
                    </TableCell>
                    <TableCell align="right">{stat.avgWinRate?.toFixed(1)}%</TableCell>
                    <TableCell align="right" sx={{ color: 'error.main' }}>
                      {stat.avgMaxDrawdown?.toFixed(2)}%
                    </TableCell>
                    <TableCell align="right">{stat.avgSharpeRatio?.toFixed(4)}</TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={7} align="center" sx={{ py: 4 }}>
                    <Typography color="text.secondary">
                      분석 데이터가 없습니다. 투자전략 탭에서 백테스팅을 실행해주세요.
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>

      {/* 등록된 전략 목록 */}
      <Typography variant="h6" sx={{ mb: 2, mt: 4 }}>
        등록된 투자전략 목록 ({strategies.length}개)
      </Typography>
      <Card>
        <TableContainer sx={{ maxHeight: 400 }}>
          <Table stickyHeader size="small">
            <TableHead>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>전략명</TableCell>
                <TableCell>전략 유형</TableCell>
                <TableCell>설명</TableCell>
                <TableCell>상태</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {strategies.length > 0 ? (
                strategies.map((strategy) => (
                  <TableRow key={strategy.id} hover>
                    <TableCell>{strategy.id}</TableCell>
                    <TableCell>
                      <Typography fontWeight={500}>{strategy.name}</Typography>
                    </TableCell>
                    <TableCell>
                      <Chip label={strategy.strategyType} size="small" variant="outlined" color="primary" />
                    </TableCell>
                    <TableCell sx={{ maxWidth: 300 }}>
                      <Typography variant="body2" color="text.secondary" noWrap>
                        {(strategy as any).description || '-'}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip 
                        label={strategy.enabled ? '활성' : '비활성'} 
                        size="small" 
                        color={strategy.enabled ? 'success' : 'default'}
                      />
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={5} align="center" sx={{ py: 4 }}>
                    <Typography color="text.secondary">
                      등록된 전략이 없습니다.
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>
    </Box>
  );

  // 투자실행 현황 탭
  const ExecutionStatusTab = () => (
    <Box>
      {/* 최근 백테스팅 결과 통계 */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="총 분석 횟수"
            value={summary?.strategyStats?.reduce((acc, s) => acc + s.analysisCount, 0) || 0}
            icon={<Timeline />}
            color="#6495ed"
            subtitle="전체 백테스팅 횟수"
          />
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="분석된 전략"
            value={summary?.strategyStats?.filter(s => s.analysisCount > 0).length || 0}
            icon={<ShowChart />}
            color="#4ade80"
            subtitle="테스트된 전략 수"
          />
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="분석된 마켓"
            value={new Set(summary?.recentAnalyses?.map(a => a.market) || []).size}
            icon={<Storage />}
            color="#fbbf24"
            subtitle="테스트된 종목 수"
          />
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <StatCard
            title="최근 분석"
            value={summary?.recentAnalyses?.length || 0}
            icon={<PlayCircle />}
            color="#f87171"
            subtitle="최근 10건"
          />
        </Grid>
      </Grid>

      {/* 최근 백테스팅 결과 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <PlayCircle color="primary" />
        최근 백테스팅 결과
      </Typography>
      <Card>
        <TableContainer sx={{ maxHeight: 500 }}>
          <Table stickyHeader size="small">
            <TableHead>
              <TableRow>
                <TableCell>분석일시</TableCell>
                <TableCell>전략</TableCell>
                <TableCell>종목</TableCell>
                <TableCell>시간봉</TableCell>
                <TableCell>분석기간</TableCell>
                <TableCell align="right">수익률</TableCell>
                <TableCell align="right">승률</TableCell>
                <TableCell align="right">거래횟수</TableCell>
                <TableCell align="right">MDD</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {summary?.recentAnalyses && summary.recentAnalyses.length > 0 ? (
                summary.recentAnalyses.map((analysis: StrategyPerformance) => (
                  <TableRow key={analysis.id} hover>
                    <TableCell>{formatDateTime(analysis.analysisDate)}</TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight={500}>
                        {analysis.strategyName}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip label={analysis.market} size="small" variant="outlined" />
                    </TableCell>
                    <TableCell>{analysis.timeUnit}</TableCell>
                    <TableCell>
                      <Typography variant="caption">
                        {formatDate(analysis.analysisPeriodStart)} ~ {formatDate(analysis.analysisPeriodEnd)}
                      </Typography>
                    </TableCell>
                    <TableCell align="right">
                      <Typography
                        sx={{ 
                          color: analysis.returnRate >= 0 ? 'success.main' : 'error.main',
                          fontWeight: 600 
                        }}
                      >
                        {analysis.returnRate?.toFixed(2)}%
                      </Typography>
                    </TableCell>
                    <TableCell align="right">{analysis.winRate?.toFixed(1)}%</TableCell>
                    <TableCell align="right">{analysis.totalTrades}</TableCell>
                    <TableCell align="right" sx={{ color: 'error.main' }}>
                      {analysis.maxDrawdown?.toFixed(2)}%
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={9} align="center" sx={{ py: 4 }}>
                    <Typography color="text.secondary">
                      실행된 백테스팅이 없습니다. 투자전략 탭에서 백테스팅을 실행해주세요.
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>
    </Box>
  );

  // 업비트 DB(캔들) 상세 — MySQL upbit_candles
  const upbitDbProgressActive = upbitDbLoading || upbitDbRefreshing;
  const UpbitDatabaseTab = () => (
    <Box>
      {/* 고정 높이 슬롯: 갱신 시 바가 사라져도 아래 콘텐츠가 움직이지 않음 */}
      <Box
        sx={{
          position: 'sticky',
          top: 0,
          zIndex: 2,
          mb: 1,
          height: 4,
          borderRadius: 1,
          overflow: 'hidden',
        }}
      >
        <LinearProgress
          variant={upbitDbProgressActive ? 'indeterminate' : 'determinate'}
          {...(upbitDbProgressActive ? {} : { value: 0 })}
          sx={{ height: 4, borderRadius: 1 }}
        />
      </Box>
      {upbitDbLoading && !upbitDb && (
        <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
          DB 집계 최초 로딩…
        </Typography>
      )}
      <Box
        sx={{
          display: 'flex',
          flexWrap: 'wrap',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 1,
          mb: 2,
        }}
      >
        <Typography variant="body2" color="text.secondary" component="div">
          <Chip
            size="small"
            color="info"
            variant="outlined"
            label={`${(UPBIT_DB_POLL_MS / 1000).toFixed(0)}초마다 DB 현황 자동 갱신 (탭이 보일 때만)`}
            sx={{ mr: 1, mb: 0.5 }}
          />
          {upbitLastRefreshedAt && (
            <span>
              대시보드 API 폴링:{' '}
              <strong>
                {upbitLastRefreshedAt.toLocaleString('ko-KR', { hour12: false })}
                {upbitDbRefreshing && ' (불러오는 중…)'}
              </strong>
            </span>
          )}
          {upbitDb?.candlesMaxUpdatedAt && (
            <span style={{ display: 'block', marginTop: 6 }}>
              <Chip
                size="small"
                color="primary"
                variant="outlined"
                label={`upbit_candles DB 최신 쓰기(updated_at): ${upbitDb.candlesMaxUpdatedAt}`}
              />
            </span>
          )}
        </Typography>
      </Box>
      {upbitDbError && (
        <Alert severity="warning" sx={{ mb: 2 }}>
          {upbitDbError} (백엔드 <code>/api/upbit/db-status</code> 확인)
        </Alert>
      )}
      {upbitDb && (
        <>
          <Grid container spacing={2} sx={{ mb: 3 }}>
            <Grid item xs={12} sm={6} md={3}>
              <Card>
                <CardContent>
                  <Typography variant="body2" color="text.secondary" gutterBottom>
                    upbit_candles 총 행
                  </Typography>
                  <Typography variant="h4" color="primary.main" fontWeight={700}>
                    {upbitDb.totalCandleRows.toLocaleString()}
                  </Typography>
                  {upbitDb.candlesMaxUpdatedAt && (
                    <Typography variant="caption" color="text.secondary" display="block" sx={{ mt: 0.5 }}>
                      최신 행 쓰기(UTC+9): {upbitDb.candlesMaxUpdatedAt}
                    </Typography>
                  )}
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Card>
                <CardContent>
                  <Typography variant="body2" color="text.secondary" gutterBottom>
                    DB에 있는 마켓 수
                  </Typography>
                  <Typography variant="h4" color="info.main" fontWeight={700}>
                    {upbitDb.distinctMarketCount}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Card>
                <CardContent>
                  <Typography variant="body2" color="text.secondary" gutterBottom>
                    REST 백필(비상)
                  </Typography>
                  <Chip
                    label={upbitDb.fallbackToRest === 'true' ? 'upbit.fallback-to-rest=true' : '꺼짐 (DB만)'}
                    color={upbitDb.fallbackToRest === 'true' ? 'warning' : 'success'}
                    size="small"
                    sx={{ mt: 0.5 }}
                  />
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Card>
                <CardContent>
                  <Typography variant="body2" color="text.secondary" gutterBottom>
                    체결 아카이브(upbit_trades)
                  </Typography>
                  <Typography variant="h4" color="text.secondary" fontWeight={700}>
                    {upbitDb.tradeArchiveRows.toLocaleString()} 행
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          </Grid>

          <Typography variant="h6" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <Hub color="action" />
            캔들 유형별 행 수 (candleType:unit)
          </Typography>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 3 }}>
            {upbitDb.candleRowsByCandleType.length === 0 && (
              <Chip label="캔들 없음" variant="outlined" />
            )}
            {upbitDb.candleRowsByCandleType.map((c) => (
              <Tooltip key={c.candleTypeKey} title="upbit_candles">
                <Chip
                  label={`${c.candleTypeKey} · ${c.count.toLocaleString()}`}
                  variant="outlined"
                  size="small"
                />
              </Tooltip>
            ))}
          </Box>

          <Typography variant="h6" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <Storage color="action" />
            마켓별 캔들 총 행
          </Typography>
          <TableContainer component={Paper} variant="outlined" sx={{ mb: 3, maxHeight: 200 }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>마켓</TableCell>
                  <TableCell align="right">캔들 행</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {upbitDb.candleRowsByMarket.map((r) => (
                  <TableRow key={r.market} hover>
                    <TableCell>
                      <Chip label={r.market} size="small" />
                    </TableCell>
                    <TableCell align="right">{r.count.toLocaleString()}</TableCell>
                  </TableRow>
                ))}
                {upbitDb.candleRowsByMarket.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={2} align="center">
                      데이터 없음
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>

          <Typography variant="h6" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <ShowChart color="primary" />
            시계열 상세 (마켓·봉·최소·최대 KST)
          </Typography>
          <TextField
            size="small"
            fullWidth
            placeholder="마켓, 시간봉 라벨, 캔들타입으로 필터"
            value={upbitSeriesFilter}
            onChange={(e) => setUpbitSeriesFilter(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Search fontSize="small" />
                </InputAdornment>
              ),
            }}
            sx={{ mb: 2 }}
          />
          <TableContainer component={Paper} variant="outlined" sx={{ maxHeight: 480, mb: 3 }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>마켓</TableCell>
                  <TableCell>봉</TableCell>
                  <TableCell>candleType</TableCell>
                  <TableCell align="right">unit(분)</TableCell>
                  <TableCell>최소( KST )</TableCell>
                  <TableCell>최대( KST )</TableCell>
                  <TableCell align="right">행</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {filteredUpbitSeries.map((s) => (
                  <TableRow key={`${s.market}-${s.candleType}-${s.unit ?? 'x'}`} hover>
                    <TableCell>
                      <Chip label={s.market} size="small" variant="outlined" />
                    </TableCell>
                    <TableCell>
                      <Chip label={s.timeFrameLabel} size="small" color="primary" variant="outlined" />
                    </TableCell>
                    <TableCell>{s.candleType}</TableCell>
                    <TableCell align="right">{s.unit ?? '—'}</TableCell>
                    <TableCell sx={{ whiteSpace: 'nowrap' }}>
                      {s.minKst ? formatDateTime(s.minKst) : '—'}
                    </TableCell>
                    <TableCell sx={{ whiteSpace: 'nowrap' }}>
                      {s.maxKst ? formatDateTime(s.maxKst) : '—'}
                    </TableCell>
                    <TableCell align="right">{s.count.toLocaleString()}</TableCell>
                  </TableRow>
                ))}
                {filteredUpbitSeries.length === 0 && !upbitDbLoading && (
                  <TableRow>
                    <TableCell colSpan={7} align="center" sx={{ py: 3 }}>
                      조건에 맞는 시계열이 없습니다
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
            총 {upbitDb.series.length}개 시계열 · 필터 {filteredUpbitSeries.length}개
          </Typography>

          {upbitDb.ingestionByStatus && upbitDb.ingestionByStatus.length > 0 && (
            <>
              <Typography variant="h6" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
                <CloudSync color="action" />
                배치 수집 상태( upbit_ingestion_state )
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2 }}>
                {upbitDb.ingestionByStatus.map((g) => (
                  <Chip key={g.status} label={`${g.status}: ${g.count}`} size="small" variant="outlined" />
                ))}
              </Box>
              <TableContainer component={Paper} variant="outlined" sx={{ maxHeight: 240, mb: 3 }}>
                <Table size="small" stickyHeader>
                  <TableHead>
                    <TableRow>
                      <TableCell>source</TableCell>
                      <TableCell>market</TableCell>
                      <TableCell>unit_path</TableCell>
                      <TableCell>date</TableCell>
                      <TableCell>status</TableCell>
                      <TableCell>에러(일부)</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {upbitDb.recentIngestion.map((r, i) => (
                      <TableRow key={`${r.market}-${r.targetDate}-${i}`} hover>
                        <TableCell>{r.sourceKey}</TableCell>
                        <TableCell>{r.market}</TableCell>
                        <TableCell>{r.unitPath}</TableCell>
                        <TableCell>{r.targetDate || '—'}</TableCell>
                        <TableCell>
                          <Chip label={r.status} size="small" />
                        </TableCell>
                        <TableCell sx={{ maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis' }} title={r.lastError || ''}>
                          {r.lastError || '—'}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </>
          )}

          <Typography variant="h6" sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <Schedule color="action" />
            WebSocket 구독( upbit_ws_subscription )
          </Typography>
          <TableContainer component={Paper} variant="outlined" sx={{ maxHeight: 280 }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>마켓</TableCell>
                  <TableCell>interval</TableCell>
                  <TableCell>활성</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {upbitDb.wsSubscriptions.map((w) => (
                  <TableRow key={`${w.market}-${w.intervalCode}`} hover>
                    <TableCell>{w.market}</TableCell>
                    <TableCell>{w.intervalCode}</TableCell>
                    <TableCell>
                      <Chip label={w.active ? 'ON' : 'OFF'} size="small" color={w.active ? 'success' : 'default'} />
                    </TableCell>
                  </TableRow>
                ))}
                {upbitDb.wsSubscriptions.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={3} align="center" sx={{ py: 2 }}>
                      등록된 WS 구독이 없습니다. <code>POST /api/upbit/ws-subscriptions</code> 로 추가할 수 있습니다.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </>
      )}
    </Box>
  );

  // 스케쥴러 현황 탭
  const SchedulerStatusTab = () => (
    <Box>
      {/* 스케쥴러 상태 */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
                <Schedule color="primary" />
                스케쥴러 상태
              </Typography>
              {schedulerStatus ? (
                <Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                    <Typography variant="body2" color="text.secondary">상태:</Typography>
                    <Chip
                      icon={schedulerStatus.isRunning ? <CheckCircle /> : <Pending />}
                      label={schedulerStatus.isRunning ? '실행 중' : '대기 중'}
                      color={schedulerStatus.isRunning ? 'success' : 'default'}
                      size="small"
                    />
                  </Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                    <Typography variant="body2" color="text.secondary">활성화:</Typography>
                    <Chip
                      label={schedulerStatus.isEnabled ? '활성' : '비활성'}
                      color={schedulerStatus.isEnabled ? 'primary' : 'default'}
                      size="small"
                      variant="outlined"
                    />
                  </Box>
                  {schedulerStatus.nextRunTime && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                      <Typography variant="body2" color="text.secondary">다음 실행:</Typography>
                      <Typography variant="body2">{formatDateTime(schedulerStatus.nextRunTime)}</Typography>
                    </Box>
                  )}
                  {schedulerStatus.lastRunTime && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                      <Typography variant="body2" color="text.secondary">마지막 실행:</Typography>
                      <Typography variant="body2">{formatDateTime(schedulerStatus.lastRunTime)}</Typography>
                    </Box>
                  )}
                </Box>
              ) : (
                <Typography color="text.secondary">스케쥴러 정보를 불러올 수 없습니다.</Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
                <Timeline color="info" />
                실행 통계
              </Typography>
              {schedulerStatus ? (
                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <Paper variant="outlined" sx={{ p: 2, textAlign: 'center' }}>
                      <Typography variant="h4" color="success.main">
                        {schedulerStatus.successCount || 0}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">성공</Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={6}>
                    <Paper variant="outlined" sx={{ p: 2, textAlign: 'center' }}>
                      <Typography variant="h4" color="error.main">
                        {schedulerStatus.failCount || 0}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">실패</Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={12}>
                    <Paper variant="outlined" sx={{ p: 2, textAlign: 'center' }}>
                      <Typography variant="h4" color="primary.main">
                        {schedulerStatus.totalRunCount || 0}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">총 실행 횟수</Typography>
                    </Paper>
                  </Grid>
                </Grid>
              ) : (
                <Typography color="text.secondary">통계 정보를 불러올 수 없습니다.</Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 최근 실행 로그 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Storage color="action" />
        최근 실행 로그
      </Typography>
      <Card>
        <CardContent>
          {schedulerStatus?.recentLogs && schedulerStatus.recentLogs.length > 0 ? (
            <Box sx={{ 
              bgcolor: 'rgba(0,0,0,0.2)', 
              p: 2, 
              borderRadius: 1, 
              maxHeight: 300, 
              overflow: 'auto',
              fontFamily: 'monospace'
            }}>
              {schedulerStatus.recentLogs.map((log, index) => (
                <Typography 
                  key={index} 
                  variant="body2" 
                  sx={{ 
                    fontSize: '0.75rem',
                    color: log.includes('ERROR') || log.includes('실패') ? 'error.main' : 
                           log.includes('SUCCESS') || log.includes('완료') ? 'success.main' : 'text.primary'
                  }}
                >
                  {log}
                </Typography>
              ))}
            </Box>
          ) : (
            <Typography color="text.secondary" align="center" sx={{ py: 4 }}>
              실행 로그가 없습니다.
            </Typography>
          )}
        </CardContent>
      </Card>
    </Box>
  );

  return (
    <Box className="fade-in">
      <Typography variant="h4" sx={{ mb: 3, display: 'flex', alignItems: 'center', gap: 1 }}>
        <ShowChart color="primary" />
        대시보드
      </Typography>

      {/* 탭 메뉴 */}
      <Paper sx={{ mb: 2 }}>
        <Tabs 
          value={activeTab} 
          onChange={(_, v) => setActiveTab(v)}
          variant="fullWidth"
          sx={{ borderBottom: 1, borderColor: 'divider' }}
        >
          <Tab 
            icon={<DataUsage />} 
            label="데이터 현황" 
            iconPosition="start"
          />
          <Tab 
            icon={<ShowChart />} 
            label="투자전략 현황" 
            iconPosition="start"
          />
          <Tab 
            icon={<PlayCircle />} 
            label="투자실행 현황" 
            iconPosition="start"
          />
          <Tab 
            icon={<Schedule />} 
            label="스케쥴러 현황" 
            iconPosition="start"
          />
          <Tab
            icon={<Hub />}
            label="업비트 DB"
            iconPosition="start"
          />
          <Tab
            icon={<TableChart />}
            label="데이터 DB"
            iconPosition="start"
          />
          <Tab
            icon={<Laptop />}
            label="시스템"
            iconPosition="start"
          />
        </Tabs>
      </Paper>

      {/* 탭 패널 */}
      <TabPanel value={activeTab} index={0}>
        <DataStatusTab />
      </TabPanel>
      <TabPanel value={activeTab} index={1}>
        <StrategyStatusTab />
      </TabPanel>
      <TabPanel value={activeTab} index={2}>
        <ExecutionStatusTab />
      </TabPanel>
      <TabPanel value={activeTab} index={3}>
        <SchedulerStatusTab />
      </TabPanel>
      <TabPanel value={activeTab} index={4}>
        <UpbitDatabaseTab />
      </TabPanel>
      <TabPanel value={activeTab} index={5}>
        <DashboardDbExplorerTab />
      </TabPanel>
      <TabPanel value={activeTab} index={6}>
        <SystemMonitorTab />
      </TabPanel>
    </Box>
  );
};

export default DashboardPage;
