import { Typography, Box, Chip } from '@mui/material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { MonitorHeartOutlined } from '@mui/icons-material';
import { adminApi } from '../../services/admin';
import { useCountUp } from '../../hooks/useCountUp';
import { usePermissionContext } from '../../contexts/PermissionContext';
import { WidgetCard } from '../templates/WidgetCard';
import { StatSkeleton } from '../templates/SkeletonPresets';

function AdminStatusWidget() {
  const { hasPermission } = usePermissionContext();
  const navigate = useNavigate();

  const canView = hasPermission('admin:view');

  const { data } = useQuery({
    queryKey: ['admin-status-summary'],
    queryFn: () => adminApi.getStatusSummary(),
    refetchInterval: 30_000,
    enabled: canView,
  });

  const up = useCountUp(data?.up ?? 0);
  const total = useCountUp(data?.total ?? 0);

  if (!canView) return null;

  const allUp = data && data.up === data.total;
  const majorityDown = data && data.total > 0 && data.up < data.total / 2;
  const color = allUp ? 'success' : majorityDown ? 'error' : 'warning';

  return (
    <WidgetCard
      title="Service Status"
      icon={<MonitorHeartOutlined />}
      isLoading={!data}
      skeleton={<StatSkeleton />}
      onClick={() => navigate('/admin')}
    >
      <Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5, mb: 1 }}>
        <Typography variant="h3" component="span" sx={{ fontWeight: 700 }}>
          {up}
        </Typography>
        <Typography variant="h5" component="span" color="text.secondary">
          / {total}
        </Typography>
        <Typography variant="body2" color="text.secondary" sx={{ ml: 0.5 }}>
          Services online
        </Typography>
      </Box>

      <Chip
        label={allUp ? 'Alle aktiv' : majorityDown ? 'Kritisch' : 'Teilweise gestört'}
        color={color}
        size="small"
        variant="outlined"
      />
    </WidgetCard>
  );
}

export default AdminStatusWidget;
