import React, { useEffect } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Grid,
  Chip,
  CircularProgress,
  Alert,
  Divider,
  Paper,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import {
  Storage as StorageIcon,
  Memory as RedisIcon,
  Search as SearchIcon,
  Computer as DocEngineIcon,
  Favorite as HeartbeatIcon,
  Settings as DefaultIcon,
} from '@mui/icons-material';
import { useSystemStatus } from '@/hooks/setting-hooks';
import type { ISystemStatus } from '@/interfaces/database/user-setting';

// 状态颜色映射
const STATUS_COLORS = {
  green: 'success' as const,
  red: 'error' as const,
  yellow: 'warning' as const,
};

// 组件标题映射
const TITLE_MAP = {
  doc_engine: 'Doc Engine',
  storage: 'Object Storage',
  redis: 'Redis',
  database: 'Database',
  es: 'Elasticsearch',
  task_executor_heartbeat: 'Task Executor',
};


// 图标映射
const ICON_MAP = {
  es: SearchIcon,
  doc_engine: DocEngineIcon,
  redis: RedisIcon,
  storage: StorageIcon,
  task_executor_heartbeat: HeartbeatIcon,
};

function SystemSetting() {
  const { t } = useTranslation();
  const { systemStatus, loading, error, fetchSystemStatus } = useSystemStatus();
  const componentTitleMap: Record<string, string> = {
    'doc_engine': t('setting.docEngine'),
    'object_storage': t('setting.objectStorage'),
    'redis': t('setting.redis'),
    'database': t('setting.database'),
    'elasticsearch': t('setting.elasticsearch'),
    'task_executor': t('setting.taskExecutor'),
  };

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

  const renderSystemInfo = (key: string, info: any) => {
    // 跳过task_executor_heartbeat，因为它需要特殊的图表组件
    if (key.startsWith('task_executor_heartbeat')) {
      return null;
    }

    const IconComponent = ICON_MAP[key as keyof typeof ICON_MAP] || DefaultIcon;
    const title = TITLE_MAP[key as keyof typeof TITLE_MAP] || key;
    const status = info?.status || 'unknown';
    const chipColor = STATUS_COLORS[status as keyof typeof STATUS_COLORS] || 'default';

    return (
      <Grid size={12} key={key}>
        <Card
          sx={{
            height: '100%',
            transition: 'all 0.3s ease',
            '&:hover': {
              transform: 'translateY(-4px)',
              boxShadow: 4,
            }
          }}
        >
          <CardContent>
            <Box display="flex" alignItems="center" gap={2} mb={2}>
              <Box
                sx={{
                  p: 1,
                  borderRadius: 2,
                  backgroundColor: 'primary.main',
                  color: 'white',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <IconComponent />
              </Box>
              <Typography variant="h6" component="h3" sx={{ flexGrow: 1 }}>
                {title}
              </Typography>
              <Chip
                label={status.toUpperCase()}
                color={chipColor}
                size="small"
                variant="filled"
                sx={{ fontWeight: 'bold' }}
              />
            </Box>

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

            <Box>
              {Object.keys(info)
                .filter((x) => x !== 'status')
                .map((x) => (
                  <Box
                    key={x}
                    display="flex"
                    justifyContent="space-between"
                    alignItems="center"
                    mb={1}
                    sx={{
                      p: 1,
                      borderRadius: 1,
                      '&:hover': {
                        backgroundColor: 'grey.50',
                      }
                    }}
                  >
                    <Typography variant="body2" color="text.secondary" fontWeight="medium">
                      {x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}:
                    </Typography>
                    <Typography
                      variant="body2"
                      color={x === 'error' ? 'error' : 'text.primary'}
                      fontWeight="bold"
                    >
                      {typeof info[x] === 'number'
                        ? info[x].toFixed(2)
                        : (info[x] != null ? String(info[x]) : 'N/A')
                      }
                      {x === 'elapsed' && ' ms'}
                    </Typography>
                  </Box>
                ))}
            </Box>
          </CardContent>
        </Card>
      </Grid>
    );
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box p={3}>
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      </Box>
    );
  }

  return (
    <Box p={3}>
      <Box mb={4}>
        <Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold' }}>
          {t('setting.systemStatus')}
        </Typography>

        <Typography variant="body1" color="text.secondary" paragraph>
          {t('setting.systemStatusDescription')}
        </Typography>
      </Box>

      {systemStatus ? (
        <Grid container spacing={3}>
          {Object.keys(systemStatus).map((key) =>
            renderSystemInfo(key, systemStatus[key as keyof ISystemStatus])
          )}
        </Grid>
      ) : (
        <Alert severity="info" sx={{ mt: 2 }}>
          {t('setting.noSystemStatusData')}
        </Alert>
      )}
    </Box>
  );
}

export default SystemSetting;
