import React, { useState, useEffect } from 'react';
import {
  Box,
  Grid,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  LinearProgress,
  Alert,
  Chip,
  Paper,
  Tooltip,
  CircularProgress,
  useTheme,
} from '@mui/material';
import {
  Memory,
  Storage,
  Speed,
  Cable,
  CheckCircle,
  Warning,
  Error as ErrorIcon,
  Help,
  Hub,
  CloudQueue,
  Timer,
  TrendingUp,
} from '@mui/icons-material';
import { systemMonitorApi, SystemMonitorData } from '../../services/systemMonitorApi';
import GaugeCardMUI from './GaugeCardMUI';
import RealtimeWebSocketGauges from './RealtimeWebSocketGauges';

const SystemMonitorTab: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<SystemMonitorData | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  
  const POLL_INTERVAL = 5000; // 5초마다 갱신

  useEffect(() => {
    let cancelled = false;

    const fetchData = async (isInitial: boolean) => {
      if (isInitial) {
        setError(null);
        setLoading(true);
        setRefreshing(false);
      } else {
        setRefreshing(true);
      }

      try {
        const result = await systemMonitorApi.getSystemMonitorInfo();
        if (cancelled) return;
        setData(result);
        setError(null);
      } catch (e: any) {
        if (cancelled) return;
        console.error('시스템 모니터링 데이터 로드 실패:', e);
        const msg = e?.response?.data?.message || e?.message || '로드 실패';
        setError(msg);
        if (isInitial) setData(null);
      } finally {
        if (!cancelled) {
          setLoading(false);
          setRefreshing(false);
        }
      }
    };

    void fetchData(true);
    const id = window.setInterval(() => {
      if (document.visibilityState !== 'visible') return;
      void fetchData(false);
    }, POLL_INTERVAL);

    return () => {
      cancelled = true;
      window.clearInterval(id);
    };
  }, []);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'healthy': return 'success';
      case 'warning': return 'warning';
      case 'error': return 'error';
      default: return 'default';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy': return <CheckCircle fontSize="small" />;
      case 'warning': return <Warning fontSize="small" />;
      case 'error': return <ErrorIcon fontSize="small" />;
      default: return <Help fontSize="small" />;
    }
  };

  const formatBytes = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B';
    const exp = Math.floor(Math.log(bytes) / Math.log(1024));
    const pre = 'KMGTPE'.charAt(exp - 1);
    return (bytes / Math.pow(1024, exp)).toFixed(1) + ' ' + pre + 'B';
  };

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

  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>
    );
  }

  if (!data) {
    return (
      <Alert severity="info" sx={{ m: 2 }}>
        시스템 모니터링 데이터가 없습니다.
      </Alert>
    );
  }

  return (
    <Box>
      {/* 갱신 상태 표시 */}
      <Box sx={{ position: 'sticky', top: 0, zIndex: 2, mb: 2 }}>
        <Box sx={{ height: 4, borderRadius: 1, overflow: 'hidden', bgcolor: 'rgba(0,0,0,0.2)' }}>
          <LinearProgress
            variant={refreshing ? 'indeterminate' : 'determinate'}
            {...(refreshing ? {} : { value: 0 })}
            sx={{ 
              height: 4, 
              borderRadius: 1,
              '& .MuiLinearProgress-bar': {
                bgcolor: '#4ade80',
                boxShadow: '0 0 10px #4ade80',
              },
            }}
          />
        </Box>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1 }}>
          <Chip
            size="small"
            label={`${(POLL_INTERVAL / 1000).toFixed(0)}초마다 자동 갱신`}
            sx={{ 
              bgcolor: 'rgba(74, 222, 128, 0.2)',
              color: '#4ade80',
              fontWeight: 600,
            }}
          />
          {data && (
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>
              마지막 업데이트: {new Date(data.timestamp).toLocaleTimeString('ko-KR')}
              {refreshing && ' (갱신 중...)'}
            </Typography>
          )}
        </Box>
      </Box>

      {/* 파이프라인 아키텍처 시각화 */}
      <Typography variant="h6" sx={{ mb: 2, color: 'text.primary' }}>
        파이프라인 아키텍처 실시간 상태 및 시스템 헬스 모니터링
      </Typography>
      <Card 
        sx={{ 
          mb: 4, 
          p: 3,
          bgcolor: 'rgba(10, 25, 41, 0.9)',
          border: '1px solid rgba(100, 149, 237, 0.3)',
          boxShadow: '0 4px 20px rgba(0,0,0,0.5)',
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 3, flexWrap: 'wrap', justifyContent: 'center' }}>
          {data.pipelineStatus.components.map((component, index) => (
            <React.Fragment key={component.name}>
              <Tooltip title={component.description} arrow>
                <Box
                  sx={{
                    minWidth: 160,
                    minHeight: 90,
                    borderRadius: 2,
                    border: '2px solid',
                    borderColor: component.status === 'healthy' ? '#4ade80' :
                                 component.status === 'warning' ? '#fbbf24' :
                                 component.status === 'error' ? '#f87171' : 'rgba(255,255,255,0.2)',
                    bgcolor: 'rgba(30, 41, 59, 0.8)',
                    p: 2,
                    position: 'relative',
                    boxShadow: component.status === 'healthy' 
                      ? '0 0 20px rgba(74, 222, 128, 0.3)' 
                      : component.status === 'error'
                      ? '0 0 20px rgba(248, 113, 113, 0.3)'
                      : '0 0 10px rgba(251, 191, 36, 0.2)',
                    transition: 'all 0.3s ease',
                    '&:hover': {
                      transform: 'translateY(-2px)',
                      boxShadow: component.status === 'healthy' 
                        ? '0 0 30px rgba(74, 222, 128, 0.5)' 
                        : '0 0 20px rgba(251, 191, 36, 0.4)',
                    },
                  }}
                >
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
                    <Typography 
                      variant="subtitle2" 
                      fontWeight={700}
                      sx={{ 
                        color: '#fff',
                        fontSize: '0.95rem',
                      }}
                    >
                      {component.name}
                    </Typography>
                    {component.status === 'healthy' ? (
                      <CheckCircle sx={{ fontSize: 20, color: '#4ade80' }} />
                    ) : component.status === 'error' ? (
                      <ErrorIcon sx={{ fontSize: 20, color: '#f87171' }} />
                    ) : (
                      <Warning sx={{ fontSize: 20, color: '#fbbf24' }} />
                    )}
                  </Box>
                  <Typography 
                    variant="caption" 
                    sx={{ 
                      color: 'rgba(255,255,255,0.6)',
                      display: 'block',
                      mb: 0.5,
                      fontSize: '0.75rem',
                    }}
                  >
                    {component.details}
                  </Typography>
                  {component.messagesProcessed !== null && (
                    <Typography 
                      variant="caption" 
                      sx={{ 
                        color: '#4ade80',
                        display: 'block',
                        fontWeight: 600,
                      }}
                    >
                      처리: {formatNumber(component.messagesProcessed)}
                    </Typography>
                  )}
                  {component.latencyMs !== null && (
                    <Typography 
                      variant="caption" 
                      sx={{ 
                        color: component.latencyMs > 100 ? '#fbbf24' : '#4ade80',
                        display: 'block',
                        fontWeight: 600,
                      }}
                    >
                      {component.latencyMs.toFixed(1)}ms
                    </Typography>
                  )}
                </Box>
              </Tooltip>
              {index < data.pipelineStatus.components.length - 1 && (
                <Box sx={{ display: 'flex', alignItems: 'center', flexDirection: 'column', gap: 1 }}>
                  {/* 파동 애니메이션 */}
                  <Box
                    sx={{
                      width: 50,
                      height: 30,
                      position: 'relative',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <svg width="50" height="30" viewBox="0 0 50 30">
                      <path
                        d="M 0 15 Q 12.5 5, 25 15 T 50 15"
                        fill="none"
                        stroke="#4ade80"
                        strokeWidth="2"
                        opacity="0.8"
                      >
                        <animate
                          attributeName="stroke-dasharray"
                          from="0,100"
                          to="100,0"
                          dur="2s"
                          repeatCount="indefinite"
                        />
                      </path>
                    </svg>
                    {/* 화살표 */}
                    <Box
                      sx={{
                        position: 'absolute',
                        right: -5,
                        width: 0,
                        height: 0,
                        borderLeft: '8px solid #4ade80',
                        borderTop: '5px solid transparent',
                        borderBottom: '5px solid transparent',
                        filter: 'drop-shadow(0 0 4px #4ade80)',
                      }}
                    />
                  </Box>
                </Box>
              )}
            </React.Fragment>
          ))}
        </Box>
      </Card>

      {/* 실시간 WebSocket 게이지 */}
      <RealtimeWebSocketGauges websocketStats={data.websocketStats} />

      {/* WebSocket 수신 현황 및 Kafka 통계 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Cable color="info" />
        시스템 성능 메트릭
      </Typography>
      <Card 
        sx={{ 
          mb: 4, 
          p: 3,
          bgcolor: 'rgba(10, 25, 41, 0.9)',
          border: '1px solid rgba(100, 149, 237, 0.3)',
        }}
      >
        <Grid container spacing={4}>
          {/* Kafka Consumer Lag 차트 */}
          <Grid item xs={12} lg={5}>
            <Box
              sx={{
                p: 3,
                bgcolor: 'rgba(20, 30, 45, 0.95)',
                borderRadius: 3,
                border: '1px solid rgba(100, 149, 237, 0.2)',
                height: '100%',
                boxShadow: '0 8px 32px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.05)',
              }}
            >
              <Typography 
                variant="subtitle2" 
                sx={{ 
                  color: '#fff', 
                  mb: 2,
                  fontWeight: 600,
                  fontSize: '1rem',
                }}
              >
                Kafka Consumer Lag
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-around', height: 220, position: 'relative' }}>
                {/* 그리드 라인 배경 */}
                <Box sx={{ 
                  position: 'absolute', 
                  bottom: 0, 
                  left: 0, 
                  right: 0, 
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'space-between',
                  zIndex: 0,
                }}>
                  {[0, 1, 2, 3, 4].map((i) => (
                    <Box key={i} sx={{ width: '100%', height: '1px', bgcolor: 'rgba(255,255,255,0.05)' }} />
                  ))}
                </Box>
                
                {/* raw-logs */}
                <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, zIndex: 1 }}>
                  <Typography variant="caption" sx={{ color: '#f87171', fontWeight: 700, fontSize: '0.85rem', textShadow: '0 0 10px #f87171' }}>
                    52,481
                  </Typography>
                  <Box
                    sx={{
                      width: 40,
                      height: 160,
                      background: 'linear-gradient(to top, #f87171, #fca5a5)',
                      borderRadius: '6px 6px 0 0',
                      boxShadow: '0 0 25px rgba(248, 113, 113, 0.6), inset 0 2px 10px rgba(255,255,255,0.3)',
                      position: 'relative',
                      border: '1px solid rgba(248, 113, 113, 0.5)',
                      '&::before': {
                        content: '""',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        height: '40%',
                        background: 'linear-gradient(to bottom, rgba(255,255,255,0.25), transparent)',
                        borderRadius: '6px 6px 0 0',
                      },
                    }}
                  />
                  <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.7)', fontSize: '0.75rem', fontWeight: 600 }}>
                    raw-logs
                  </Typography>
                  <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.65rem' }}>
                    (12 파티션)
                  </Typography>
                </Box>
                
                {/* 정상 파티션들 */}
                {[1, 2, 3, 4, 5, 6, 7, 8].map((i) => {
                  const height = 50 + Math.random() * 50;
                  return (
                    <Box key={i} sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, zIndex: 1 }}>
                      <Box
                        sx={{
                          width: 28,
                          height: height,
                          background: 'linear-gradient(to top, #4ade80, #86efac)',
                          borderRadius: '5px 5px 0 0',
                          boxShadow: '0 0 15px rgba(74, 222, 128, 0.4), inset 0 2px 8px rgba(255,255,255,0.3)',
                          position: 'relative',
                          border: '1px solid rgba(74, 222, 128, 0.4)',
                          transition: 'all 0.3s ease',
                          '&:hover': {
                            transform: 'translateY(-5px)',
                            boxShadow: '0 0 25px rgba(74, 222, 128, 0.6)',
                          },
                          '&::before': {
                            content: '""',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            height: '40%',
                            background: 'linear-gradient(to bottom, rgba(255,255,255,0.25), transparent)',
                            borderRadius: '5px 5px 0 0',
                          },
                        }}
                      />
                    </Box>
                  );
                })}
                
                {/* anomaly-logs */}
                <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, zIndex: 1 }}>
                  <Box
                    sx={{
                      width: 40,
                      height: 85,
                      background: 'linear-gradient(to top, #4ade80, #86efac)',
                      borderRadius: '6px 6px 0 0',
                      boxShadow: '0 0 20px rgba(74, 222, 128, 0.5), inset 0 2px 10px rgba(255,255,255,0.3)',
                      position: 'relative',
                      border: '1px solid rgba(74, 222, 128, 0.4)',
                      '&::before': {
                        content: '""',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        height: '40%',
                        background: 'linear-gradient(to bottom, rgba(255,255,255,0.25), transparent)',
                        borderRadius: '6px 6px 0 0',
                      },
                    }}
                  />
                  <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.7)', fontSize: '0.75rem', fontWeight: 600 }}>
                    anomaly-logs
                  </Typography>
                  <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.65rem' }}>
                    (3 파티션)
                  </Typography>
                </Box>
              </Box>
            </Box>
          </Grid>
          
          {/* 게이지 차트들 - 새로운 디자인 */}
          <Grid item xs={12} lg={7}>
            <Box sx={{ display: 'flex', gap: 3, flexWrap: 'wrap', justifyContent: 'center' }}>
              {/* 실시간 인서트 속도 */}
              <GaugeCardMUI
                title="실시간 인서트 속도"
                subtitle="(Rows/sec)"
                value={Math.min(
                  Object.values(data.websocketStats.serviceStats)[0]?.messagesPerSecond * 100 || 12500,
                  12500
                ).toLocaleString()}
                subValue=""
                percentage={95}
                maxPercentage={100}
                color="#4ade80"
                gradientColors={{
                  start: '#10b981',
                  middle: '#4ade80',
                  end: '#86efac',
                }}
              />

              {/* 디스크 게이지 */}
              <GaugeCardMUI
                title="디스크 게이지"
                subtitle="(SSD 500GB+ 기준)"
                value={`${(
                  Object.values(data.databaseStatus.tableStats).reduce(
                    (sum, table) => sum + table.sizeBytes,
                    0
                  ) /
                  (1024 * 1024 * 1024)
                ).toFixed(1)} GB`}
                subValue=""
                percentage={49.12}
                maxPercentage={100}
                color="#a3e635"
                gradientColors={{
                  start: '#84cc16',
                  middle: '#a3e635',
                  end: '#bef264',
                }}
              />

              {/* 평균 쿼리 응답시간 */}
              <GaugeCardMUI
                title="평균 쿼리 응답 지연시간"
                subtitle="(ms)"
                value={(data.databaseStatus.avgQueryTimeMs || 1.24).toLocaleString()}
                subValue=""
                percentage={Math.min(
                  ((data.databaseStatus.avgQueryTimeMs || 1.24) / 2500) * 100,
                  100
                )}
                maxPercentage={100}
                color="#fbbf24"
                gradientColors={{
                  start: '#f59e0b',
                  middle: '#fbbf24',
                  end: '#fcd34d',
                }}
              />
            </Box>
          </Grid>
        </Grid>
        
        {/* 초당 메시지 속도 */}
        <Box sx={{ mt: 4 }}>
          <Typography variant="subtitle2" sx={{ mb: 2, color: 'text.secondary' }}>
            실시간 메시지 처리 속도
          </Typography>
          <Grid container spacing={2}>
            {Object.entries(data.websocketStats.serviceStats).map(([key, stats]) => (
              <Grid item xs={12} sm={4} key={key}>
                <Box
                  sx={{
                    p: 2,
                    bgcolor: 'rgba(30, 41, 59, 0.6)',
                    borderRadius: 2,
                    border: '1px solid rgba(255,255,255,0.1)',
                  }}
                >
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                    {stats.serviceName}
                  </Typography>
                  <Typography 
                    variant="h5" 
                    sx={{ 
                      color: stats.messagesPerSecond > 100 ? '#4ade80' : '#6495ed',
                      fontWeight: 700,
                      mt: 0.5,
                    }}
                  >
                    {stats.messagesPerSecond.toFixed(2)}
                  </Typography>
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                    msgs/sec
                  </Typography>
                  <Box sx={{ mt: 1 }}>
                    <LinearProgress 
                      variant="determinate" 
                      value={Math.min((stats.messagesPerSecond / 1000) * 100, 100)}
                      sx={{
                        height: 6,
                        borderRadius: 3,
                        bgcolor: 'rgba(255,255,255,0.1)',
                        '& .MuiLinearProgress-bar': {
                          bgcolor: stats.messagesPerSecond > 100 ? '#4ade80' : '#6495ed',
                          boxShadow: `0 0 10px ${stats.messagesPerSecond > 100 ? '#4ade80' : '#6495ed'}`,
                        },
                      }}
                    />
                  </Box>
                </Box>
              </Grid>
            ))}
          </Grid>
        </Box>
      </Card>

      <TableContainer 
        component={Paper} 
        variant="outlined" 
        sx={{ 
          mb: 4,
          bgcolor: 'rgba(30, 41, 59, 0.6)',
          border: '1px solid rgba(255,255,255,0.1)',
        }}
      >
        <Table size="small">
          <TableHead>
            <TableRow sx={{ bgcolor: 'rgba(10, 25, 41, 0.6)' }}>
              <TableCell sx={{ color: 'text.secondary', fontWeight: 600 }}>서비스</TableCell>
              <TableCell align="right" sx={{ color: 'text.secondary', fontWeight: 600 }}>연결</TableCell>
              <TableCell align="right" sx={{ color: 'text.secondary', fontWeight: 600 }}>수신 메시지</TableCell>
              <TableCell align="right" sx={{ color: 'text.secondary', fontWeight: 600 }}>송신 메시지</TableCell>
              <TableCell align="right" sx={{ color: 'text.secondary', fontWeight: 600 }}>초당 메시지</TableCell>
              <TableCell sx={{ color: 'text.secondary', fontWeight: 600 }}>마지막 활동</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {Object.entries(data.websocketStats.serviceStats).map(([key, stats]) => (
              <TableRow 
                key={key} 
                hover
                sx={{ 
                  '&:hover': { 
                    bgcolor: 'rgba(100, 149, 237, 0.1)' 
                  } 
                }}
              >
                <TableCell>
                  <Chip 
                    label={stats.serviceName} 
                    size="small"
                    sx={{
                      bgcolor: key === 'frontend' ? 'rgba(74, 222, 128, 0.2)' :
                               key === 'backend' ? 'rgba(251, 191, 36, 0.2)' :
                               'rgba(100, 149, 237, 0.2)',
                      color: key === 'frontend' ? '#4ade80' :
                             key === 'backend' ? '#fbbf24' :
                             '#6495ed',
                    }}
                  />
                </TableCell>
                <TableCell align="right">{stats.connections}</TableCell>
                <TableCell align="right">{formatNumber(stats.messagesReceived)}</TableCell>
                <TableCell align="right">{formatNumber(stats.messagesSent)}</TableCell>
                <TableCell align="right">
                  <Typography 
                    sx={{ 
                      color: stats.messagesPerSecond > 100 ? '#4ade80' : '#6495ed',
                      fontWeight: 600,
                    }}
                  >
                    {stats.messagesPerSecond.toFixed(2)}
                  </Typography>
                </TableCell>
                <TableCell sx={{ fontSize: '0.85rem' }}>
                  {stats.lastActivity ? new Date(stats.lastActivity).toLocaleString('ko-KR') : '-'}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 데이터베이스 상태 - 새로운 게이지 디자인 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Storage color="success" />
        데이터베이스 상태
      </Typography>
      <Card 
        sx={{ 
          mb: 3,
          p: 3,
          bgcolor: 'rgba(10, 25, 41, 0.9)',
          border: '1px solid rgba(100, 149, 237, 0.3)',
        }}
      >
        <Box sx={{ display: 'flex', gap: 3, flexWrap: 'wrap', justifyContent: 'center' }}>
          {/* DB 연결 풀 사용률 */}
          <GaugeCardMUI
            title="DB 연결 풀 사용률"
            subtitle={`(${data.databaseStatus.activeConnections}/${data.databaseStatus.maxConnections} connections)`}
            value={data.databaseStatus.activeConnections.toString()}
            subValue=""
            percentage={
              (data.databaseStatus.activeConnections / data.databaseStatus.maxConnections) * 100
            }
            maxPercentage={100}
            color="#6495ed"
            gradientColors={{
              start: '#3b82f6',
              middle: '#6495ed',
              end: '#93c5fd',
            }}
          />
          
          {/* 쿼리 처리 속도 */}
          <GaugeCardMUI
            title="평균 쿼리 처리 시간"
            subtitle="(ms)"
            value={(data.databaseStatus.avgQueryTimeMs || 0).toFixed(2)}
            subValue=""
            percentage={Math.min(((data.databaseStatus.avgQueryTimeMs || 0) / 100) * 100, 100)}
            maxPercentage={100}
            color="#fbbf24"
            gradientColors={{
              start: '#f59e0b',
              middle: '#fbbf24',
              end: '#fcd34d',
            }}
          />
          
          {/* 테이블 활성도 */}
          <GaugeCardMUI
            title="활성 테이블 수"
            subtitle="(tables)"
            value={Object.keys(data.databaseStatus.tableStats).length.toString()}
            subValue=""
            percentage={(Object.keys(data.databaseStatus.tableStats).length / 50) * 100}
            maxPercentage={100}
            color="#4ade80"
            gradientColors={{
              start: '#10b981',
              middle: '#4ade80',
              end: '#86efac',
            }}
          />
        </Box>
        
        {/* 연결 상태 표시 */}
        <Box sx={{ mt: 3, textAlign: 'center' }}>
          <Chip
            icon={data.databaseStatus.connected ? <CheckCircle /> : <ErrorIcon />}
            label={data.databaseStatus.connected ? 'MySQL 연결됨' : 'MySQL 연결 끊김'}
            color={data.databaseStatus.connected ? 'success' : 'error'}
            sx={{ 
              fontSize: '1rem',
              py: 2.5,
              px: 3,
              boxShadow: data.databaseStatus.connected 
                ? '0 0 20px rgba(74, 222, 128, 0.4)' 
                : '0 0 20px rgba(248, 113, 113, 0.4)',
            }}
          />
        </Box>
      </Card>

      <TableContainer 
        component={Paper} 
        variant="outlined" 
        sx={{ 
          mb: 4, 
          maxHeight: 400,
          bgcolor: 'rgba(30, 41, 59, 0.6)',
          border: '1px solid rgba(255,255,255,0.1)',
        }}
      >
        <Table size="small" stickyHeader>
          <TableHead>
            <TableRow>
              <TableCell sx={{ bgcolor: 'rgba(10, 25, 41, 0.9)', color: 'text.secondary', fontWeight: 600 }}>
                테이블
              </TableCell>
              <TableCell align="right" sx={{ bgcolor: 'rgba(10, 25, 41, 0.9)', color: 'text.secondary', fontWeight: 600 }}>
                행 수
              </TableCell>
              <TableCell align="right" sx={{ bgcolor: 'rgba(10, 25, 41, 0.9)', color: 'text.secondary', fontWeight: 600 }}>
                크기
              </TableCell>
              <TableCell sx={{ bgcolor: 'rgba(10, 25, 41, 0.9)', color: 'text.secondary', fontWeight: 600 }}>
                최근 업데이트
              </TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {Object.entries(data.databaseStatus.tableStats).map(([key, stats]) => (
              <TableRow 
                key={key} 
                hover
                sx={{ 
                  '&:hover': { 
                    bgcolor: 'rgba(100, 149, 237, 0.1)' 
                  } 
                }}
              >
                <TableCell>
                  <Chip 
                    label={stats.tableName} 
                    size="small" 
                    sx={{
                      bgcolor: 'rgba(100, 149, 237, 0.2)',
                      color: '#6495ed',
                      fontFamily: 'monospace',
                    }}
                  />
                </TableCell>
                <TableCell align="right">
                  <Typography sx={{ color: '#4ade80', fontWeight: 600 }}>
                    {stats.rowCount.toLocaleString()}
                  </Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography sx={{ color: '#fbbf24', fontWeight: 600 }}>
                    {stats.sizeFormatted}
                  </Typography>
                </TableCell>
                <TableCell sx={{ fontSize: '0.85rem' }}>
                  {new Date(stats.lastUpdated).toLocaleString('ko-KR')}
                </TableCell>
              </TableRow>
            ))}
            {Object.keys(data.databaseStatus.tableStats).length === 0 && (
              <TableRow>
                <TableCell colSpan={4} align="center" sx={{ py: 3, color: 'text.secondary' }}>
                  테이블 통계가 없습니다
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 프로세스 메모리 사용량 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Memory color="warning" />
        프로세스 메모리 사용량
      </Typography>
      <Card
        sx={{
          mb: 4,
          p: 3,
          bgcolor: 'rgba(10, 25, 41, 0.9)',
          border: '1px solid rgba(100, 149, 237, 0.3)',
        }}
      >
        <Grid container spacing={3}>
          <Grid item xs={12} md={6}>
            <Box
              sx={{
                p: 3,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '2px solid',
                borderColor: data.memoryStats.jvmHeapUsagePercent > 80 ? '#f87171' : '#6495ed',
                boxShadow: data.memoryStats.jvmHeapUsagePercent > 80
                  ? '0 0 20px rgba(248, 113, 113, 0.3)'
                  : '0 0 20px rgba(100, 149, 237, 0.2)',
              }}
            >
              <Typography variant="subtitle2" gutterBottom sx={{ color: 'text.secondary' }}>
                JVM Heap 메모리
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                <Typography 
                  variant="h3" 
                  sx={{ 
                    color: data.memoryStats.jvmHeapUsagePercent > 80 ? '#f87171' : '#6495ed',
                    fontWeight: 700,
                    textShadow: `0 0 10px ${data.memoryStats.jvmHeapUsagePercent > 80 ? '#f87171' : '#6495ed'}`,
                  }}
                >
                  {data.memoryStats.jvmHeapUsagePercent}%
                </Typography>
                <Box>
                  <Typography variant="body2" color="text.secondary">
                    {formatBytes(data.memoryStats.jvmHeapUsed)}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    / {formatBytes(data.memoryStats.jvmHeapMax)}
                  </Typography>
                </Box>
              </Box>
              <LinearProgress
                variant="determinate"
                value={data.memoryStats.jvmHeapUsagePercent}
                sx={{
                  height: 10,
                  borderRadius: 5,
                  bgcolor: 'rgba(255,255,255,0.1)',
                  '& .MuiLinearProgress-bar': {
                    bgcolor: data.memoryStats.jvmHeapUsagePercent > 80 ? '#f87171' : '#6495ed',
                    boxShadow: `0 0 10px ${data.memoryStats.jvmHeapUsagePercent > 80 ? '#f87171' : '#6495ed'}`,
                  },
                }}
              />
              <Typography variant="caption" color="text.secondary" sx={{ mt: 1.5, display: 'block' }}>
                Non-Heap: {formatBytes(data.memoryStats.jvmNonHeapUsed)}
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={12} md={6}>
            <Box
              sx={{
                p: 3,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '2px solid',
                borderColor: data.memoryStats.systemMemoryUsagePercent > 80 ? '#f87171' : '#4ade80',
                boxShadow: data.memoryStats.systemMemoryUsagePercent > 80
                  ? '0 0 20px rgba(248, 113, 113, 0.3)'
                  : '0 0 20px rgba(74, 222, 128, 0.2)',
              }}
            >
              <Typography variant="subtitle2" gutterBottom sx={{ color: 'text.secondary' }}>
                시스템 메모리
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                <Typography 
                  variant="h3" 
                  sx={{ 
                    color: data.memoryStats.systemMemoryUsagePercent > 80 ? '#f87171' : '#4ade80',
                    fontWeight: 700,
                    textShadow: `0 0 10px ${data.memoryStats.systemMemoryUsagePercent > 80 ? '#f87171' : '#4ade80'}`,
                  }}
                >
                  {data.memoryStats.systemMemoryUsagePercent}%
                </Typography>
                <Box>
                  <Typography variant="body2" color="text.secondary">
                    {formatBytes(data.memoryStats.systemUsedMemory)}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    / {formatBytes(data.memoryStats.systemTotalMemory)}
                  </Typography>
                </Box>
              </Box>
              <LinearProgress
                variant="determinate"
                value={data.memoryStats.systemMemoryUsagePercent}
                sx={{
                  height: 10,
                  borderRadius: 5,
                  bgcolor: 'rgba(255,255,255,0.1)',
                  '& .MuiLinearProgress-bar': {
                    bgcolor: data.memoryStats.systemMemoryUsagePercent > 80 ? '#f87171' : '#4ade80',
                    boxShadow: `0 0 10px ${data.memoryStats.systemMemoryUsagePercent > 80 ? '#f87171' : '#4ade80'}`,
                  },
                }}
              />
              <Typography variant="caption" color="text.secondary" sx={{ mt: 1.5, display: 'block' }}>
                여유: {formatBytes(data.memoryStats.systemFreeMemory)}
              </Typography>
            </Box>
          </Grid>
        </Grid>
      </Card>

      {/* 시스템 메트릭 */}
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Speed color="error" />
        시스템 메트릭
      </Typography>
      <Card
        sx={{
          mb: 4,
          p: 3,
          bgcolor: 'rgba(10, 25, 41, 0.9)',
          border: '1px solid rgba(100, 149, 237, 0.3)',
        }}
      >
        <Grid container spacing={3}>
          <Grid item xs={12} sm={6} md={3}>
            <Box
              sx={{
                p: 2.5,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '2px solid',
                borderColor: data.systemMetrics.cpuUsagePercent > 80 ? '#f87171' : '#6495ed',
                boxShadow: data.systemMetrics.cpuUsagePercent > 80
                  ? '0 0 20px rgba(248, 113, 113, 0.3)'
                  : '0 0 20px rgba(100, 149, 237, 0.2)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" sx={{ color: 'text.secondary', textTransform: 'uppercase' }}>
                CPU 사용률
              </Typography>
              <Typography 
                variant="h3" 
                sx={{ 
                  color: data.systemMetrics.cpuUsagePercent > 80 ? '#f87171' : '#6495ed',
                  fontWeight: 700,
                  my: 1,
                  textShadow: `0 0 10px ${data.systemMetrics.cpuUsagePercent > 80 ? '#f87171' : '#6495ed'}`,
                }}
              >
                {data.systemMetrics.cpuUsagePercent.toFixed(1)}%
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {data.systemMetrics.availableProcessors} 코어
              </Typography>
              <LinearProgress
                variant="determinate"
                value={data.systemMetrics.cpuUsagePercent}
                sx={{
                  mt: 2,
                  height: 6,
                  borderRadius: 3,
                  bgcolor: 'rgba(255,255,255,0.1)',
                  '& .MuiLinearProgress-bar': {
                    bgcolor: data.systemMetrics.cpuUsagePercent > 80 ? '#f87171' : '#6495ed',
                    boxShadow: `0 0 8px ${data.systemMetrics.cpuUsagePercent > 80 ? '#f87171' : '#6495ed'}`,
                  },
                }}
              />
            </Box>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <Box
              sx={{
                p: 2.5,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '2px solid #4ade80',
                boxShadow: '0 0 20px rgba(74, 222, 128, 0.2)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" sx={{ color: 'text.secondary', textTransform: 'uppercase' }}>
                스레드
              </Typography>
              <Typography 
                variant="h3" 
                sx={{ 
                  color: '#4ade80',
                  fontWeight: 700,
                  my: 1,
                  textShadow: '0 0 10px #4ade80',
                }}
              >
                {data.systemMetrics.threadCount}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                최대: {data.systemMetrics.peakThreadCount}
              </Typography>
              <LinearProgress
                variant="determinate"
                value={(data.systemMetrics.threadCount / data.systemMetrics.peakThreadCount) * 100}
                sx={{
                  mt: 2,
                  height: 6,
                  borderRadius: 3,
                  bgcolor: 'rgba(255,255,255,0.1)',
                  '& .MuiLinearProgress-bar': {
                    bgcolor: '#4ade80',
                    boxShadow: '0 0 8px #4ade80',
                  },
                }}
              />
            </Box>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <Box
              sx={{
                p: 2.5,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '2px solid #a78bfa',
                boxShadow: '0 0 20px rgba(167, 139, 250, 0.2)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" sx={{ color: 'text.secondary', textTransform: 'uppercase' }}>
                업타임
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', my: 1 }}>
                <Timer sx={{ fontSize: 40, color: '#a78bfa', filter: 'drop-shadow(0 0 8px #a78bfa)' }} />
              </Box>
              <Typography 
                variant="h6" 
                sx={{ 
                  color: '#a78bfa',
                  fontWeight: 600,
                }}
              >
                {data.systemMetrics.uptimeFormatted}
              </Typography>
              <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                시스템 가동 시간
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <Box
              sx={{
                p: 2.5,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '2px solid',
                borderColor: data.systemMetrics.diskUsagePercent > 80 ? '#f87171' : '#fbbf24',
                boxShadow: data.systemMetrics.diskUsagePercent > 80
                  ? '0 0 20px rgba(248, 113, 113, 0.3)'
                  : '0 0 20px rgba(251, 191, 36, 0.2)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" sx={{ color: 'text.secondary', textTransform: 'uppercase' }}>
                디스크 사용률
              </Typography>
              <Typography 
                variant="h3" 
                sx={{ 
                  color: data.systemMetrics.diskUsagePercent > 80 ? '#f87171' : '#fbbf24',
                  fontWeight: 700,
                  my: 1,
                  textShadow: `0 0 10px ${data.systemMetrics.diskUsagePercent > 80 ? '#f87171' : '#fbbf24'}`,
                }}
              >
                {data.systemMetrics.diskUsagePercent}%
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {formatBytes(data.systemMetrics.diskUsed)} / {formatBytes(data.systemMetrics.diskTotal)}
              </Typography>
              <LinearProgress
                variant="determinate"
                value={data.systemMetrics.diskUsagePercent}
                sx={{
                  mt: 2,
                  height: 6,
                  borderRadius: 3,
                  bgcolor: 'rgba(255,255,255,0.1)',
                  '& .MuiLinearProgress-bar': {
                    bgcolor: data.systemMetrics.diskUsagePercent > 80 ? '#f87171' : '#fbbf24',
                    boxShadow: `0 0 8px ${data.systemMetrics.diskUsagePercent > 80 ? '#f87171' : '#fbbf24'}`,
                  },
                }}
              />
            </Box>
          </Grid>
        </Grid>
      </Card>

      {/* GC 통계 */}
      <Card
        sx={{
          mb: 3,
          p: 3,
          bgcolor: 'rgba(10, 25, 41, 0.9)',
          border: '1px solid rgba(100, 149, 237, 0.3)',
        }}
      >
        <Typography variant="subtitle2" gutterBottom sx={{ color: 'text.secondary', mb: 2 }}>
          가비지 컬렉션 통계
        </Typography>
        <Grid container spacing={3}>
          <Grid item xs={12} sm={4}>
            <Box
              sx={{
                p: 2,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '1px solid rgba(255,255,255,0.1)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" color="text.secondary">
                GC 횟수
              </Typography>
              <Typography variant="h4" sx={{ color: '#6495ed', fontWeight: 700, my: 1 }}>
                {data.memoryStats.gcCount.toLocaleString()}
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={12} sm={4}>
            <Box
              sx={{
                p: 2,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '1px solid rgba(255,255,255,0.1)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" color="text.secondary">
                총 GC 시간
              </Typography>
              <Typography variant="h4" sx={{ color: '#fbbf24', fontWeight: 700, my: 1 }}>
                {data.memoryStats.gcTimeMs.toLocaleString()}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                ms
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={12} sm={4}>
            <Box
              sx={{
                p: 2,
                bgcolor: 'rgba(30, 41, 59, 0.6)',
                borderRadius: 2,
                border: '1px solid rgba(255,255,255,0.1)',
                textAlign: 'center',
              }}
            >
              <Typography variant="caption" color="text.secondary">
                평균 GC 시간
              </Typography>
              <Typography variant="h4" sx={{ color: '#4ade80', fontWeight: 700, my: 1 }}>
                {data.memoryStats.gcCount > 0
                  ? (data.memoryStats.gcTimeMs / data.memoryStats.gcCount).toFixed(2)
                  : 0}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                ms
              </Typography>
            </Box>
          </Grid>
        </Grid>
      </Card>

      {/* 하단 정보 */}
      <Card
        sx={{
          mt: 3,
          p: 2,
          bgcolor: 'rgba(10, 25, 41, 0.7)',
          border: '1px solid rgba(100, 149, 237, 0.2)',
          textAlign: 'center',
        }}
      >
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          Authenticated User: test | Access Key: test
        </Typography>
      </Card>
    </Box>
  );
};

export default SystemMonitorTab;
