import { Box, Card, CardContent, Typography, Chip, LinearProgress, CircularProgress, Grid } from '@mui/material';
import { useQuery } from '@tanstack/react-query';
import { adminApi } from '../../services/admin';

function formatUptime(seconds: number): string {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  const parts: string[] = [];
  if (days > 0) parts.push(`${days}d`);
  if (hours > 0) parts.push(`${hours}h`);
  parts.push(`${mins}m`);
  return parts.join(' ');
}

function formatBytes(bytes: number): string {
  const mb = bytes / (1024 * 1024);
  return `${mb.toFixed(1)} MB`;
}

function SystemHealthTab() {
  const { data: health, isLoading, isError } = useQuery({
    queryKey: ['admin', 'system', 'health'],
    queryFn: adminApi.getSystemHealth,
    refetchInterval: 30000,
  });

  if (isLoading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}><CircularProgress /></Box>;
  }

  if (isError || !health) {
    return (
      <Box sx={{ p: 4, textAlign: 'center' }}>
        <Typography color="error" gutterBottom>Systemdaten konnten nicht geladen werden.</Typography>
        <Typography variant="body2" color="text.secondary">
          Bitte versuchen Sie es später erneut.
        </Typography>
      </Box>
    );
  }

  const heapPercent = (health.memoryUsage.heapUsed / health.memoryUsage.heapTotal) * 100;

  return (
    <Box>
      <Typography variant="h6" sx={{ mb: 2 }}>Systemstatus</Typography>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>Node.js Version</Typography>
              <Chip label={health.nodeVersion} color="primary" />
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>Uptime</Typography>
              <Typography variant="h5">{formatUptime(health.uptime)}</Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>Datenbank</Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Box
                  sx={{
                    width: 12,
                    height: 12,
                    borderRadius: '50%',
                    bgcolor: health.dbStatus ? 'success.main' : 'error.main',
                  }}
                />
                <Typography>{health.dbStatus ? 'Verbunden' : 'Nicht erreichbar'}</Typography>
              </Box>
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                Groesse: {formatBytes(Number(health.dbSize))}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>Heap Speicher</Typography>
              <Typography variant="body2">
                {formatBytes(health.memoryUsage.heapUsed)} / {formatBytes(health.memoryUsage.heapTotal)}
              </Typography>
              <LinearProgress
                variant="determinate"
                value={heapPercent}
                sx={{ mt: 1, height: 8, borderRadius: 4 }}
                color={heapPercent > 85 ? 'error' : heapPercent > 70 ? 'warning' : 'primary'}
              />
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>RSS Speicher</Typography>
              <Typography variant="h5">{formatBytes(health.memoryUsage.rss)}</Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>External Speicher</Typography>
              <Typography variant="h5">{formatBytes(health.memoryUsage.external)}</Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
}

export default SystemHealthTab;
