'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  LinearProgress,
  Chip,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Alert,
  AlertTitle,
  Button,
  IconButton,
} from '@mui/material';
import {
  CheckCircle,
  Error,
  Warning,
  Refresh,
  Storage,
  Memory,
  Speed,
  CloudQueue,
  DataUsage,
  Schedule,
} from '@mui/icons-material';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';

interface ServiceStatus {
  name: string;
  status: 'healthy' | 'degraded' | 'down';
  responseTime: number;
  uptime: number;
  lastCheck: string;
}

interface SystemMetric {
  name: string;
  value: number;
  max: number;
  unit: string;
  status: 'normal' | 'warning' | 'critical';
}

interface ErrorLog {
  id: string;
  timestamp: string;
  severity: 'info' | 'warning' | 'error';
  service: string;
  message: string;
  count: number;
}

export default function HealthPage() {
  const [services, setServices] = useState<ServiceStatus[]>([]);
  const [metrics, setMetrics] = useState<SystemMetric[]>([]);
  const [errorLogs, setErrorLogs] = useState<ErrorLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastRefresh, setLastRefresh] = useState(new Date());

  useEffect(() => {
    fetchHealthData();
    const interval = setInterval(fetchHealthData, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, []);

  const fetchHealthData = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get('/admin/dashboard/health');

      setServices(response.services || []);
      setMetrics(response.metrics || []);
      setErrorLogs(response.errorLogs || []);
      setLastRefresh(new Date());
    } catch (error) {
      console.error('Failed to fetch health data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy':
      case 'normal':
        return <CheckCircle />;
      case 'degraded':
      case 'warning':
        return <Warning />;
      case 'down':
      case 'critical':
        return <Error />;
      default:
        return null;
    }
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'error':
        return 'error';
      case 'warning':
        return 'warning';
      case 'info':
        return 'info';
      default:
        return 'default';
    }
  };

  const formatTimestamp = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / 60000);

    if (minutes < 1) return 'Just now';
    if (minutes < 60) return `${minutes}m ago`;
    if (minutes < 1440) return `${Math.floor(minutes / 60)}h ago`;
    return date.toLocaleString();
  };

  const overallHealth = services.every(s => s.status === 'healthy')
    ? 'healthy'
    : services.some(s => s.status === 'down')
    ? 'critical'
    : 'degraded';

  return (
    <AdminLayout>
      <Box sx={{ mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Box>
            <Typography variant="h4" gutterBottom sx={{ fontWeight: 600 }}>
              System Health
            </Typography>
            <Typography variant="body1" color="text.secondary">
              Monitor system services and performance metrics
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Typography variant="body2" color="text.secondary">
              Last updated: {formatTimestamp(lastRefresh.toISOString())}
            </Typography>
            <IconButton onClick={fetchHealthData} disabled={loading}>
              <Refresh />
            </IconButton>
          </Box>
        </Box>
      </Box>

      {/* Overall Status Alert */}
      <Alert
        severity={getStatusColor(overallHealth) as any}
        icon={getStatusIcon(overallHealth)}
        sx={{ mb: 3 }}
      >
        <AlertTitle>
          System Status:{' '}
          {overallHealth === 'healthy'
            ? 'All Systems Operational'
            : overallHealth === 'critical'
            ? 'Critical Issues Detected'
            : 'Degraded Performance'}
        </AlertTitle>
        {overallHealth !== 'healthy' && (
          <Typography variant="body2">
            {services.filter(s => s.status !== 'healthy').length} service(s) experiencing issues
          </Typography>
        )}
      </Alert>

      {/* Service Status */}
      <Typography variant="h6" gutterBottom sx={{ mt: 4, mb: 2 }}>
        Service Status
      </Typography>
      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 2, mb: 4 }}>
        {services.map((service) => (
          <Card key={service.name}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Typography variant="subtitle1" sx={{ fontWeight: 500 }}>
                  {service.name}
                </Typography>
                <Chip
                  label={service.status}
                  color={getStatusColor(service.status) as any}
                  size="small"
                  icon={getStatusIcon(service.status) as any}
                />
              </Box>
              <Box sx={{ mt: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant="body2" color="text.secondary">
                    Response Time
                  </Typography>
                  <Typography variant="body2">
                    {service.responseTime}ms
                  </Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography variant="body2" color="text.secondary">
                    Uptime
                  </Typography>
                  <Typography variant="body2">
                    {service.uptime}%
                  </Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>
        ))}
      </Box>

      {/* System Metrics */}
      <Typography variant="h6" gutterBottom sx={{ mt: 4, mb: 2 }}>
        System Metrics
      </Typography>
      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 3, mb: 4 }}>
        {metrics.map((metric) => (
          <Paper key={metric.name} sx={{ p: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
              <Typography variant="subtitle2" color="text.secondary">
                {metric.name}
              </Typography>
              {metric.status !== 'normal' && (
                <Chip
                  label={metric.status}
                  color={getStatusColor(metric.status) as any}
                  size="small"
                />
              )}
            </Box>
            <Typography variant="h5" sx={{ mb: 1 }}>
              {metric.value}{metric.unit}
              <Typography variant="body2" component="span" color="text.secondary">
                {' '}/ {metric.max}{metric.unit}
              </Typography>
            </Typography>
            <LinearProgress
              variant="determinate"
              value={(metric.value / metric.max) * 100}
              sx={{
                height: 8,
                borderRadius: 1,
                backgroundColor: 'grey.200',
                '& .MuiLinearProgress-bar': {
                  backgroundColor:
                    metric.status === 'critical'
                      ? 'error.main'
                      : metric.status === 'warning'
                      ? 'warning.main'
                      : 'success.main',
                },
              }}
            />
          </Paper>
        ))}
      </Box>

      {/* Recent Error Logs */}
      <Typography variant="h6" gutterBottom sx={{ mt: 4, mb: 2 }}>
        Recent Events
      </Typography>
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Time</TableCell>
              <TableCell>Severity</TableCell>
              <TableCell>Service</TableCell>
              <TableCell>Message</TableCell>
              <TableCell align="center">Count</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {errorLogs.map((log) => (
              <TableRow key={log.id}>
                <TableCell>{formatTimestamp(log.timestamp)}</TableCell>
                <TableCell>
                  <Chip
                    label={log.severity}
                    color={getSeverityColor(log.severity) as any}
                    size="small"
                  />
                </TableCell>
                <TableCell>{log.service}</TableCell>
                <TableCell>{log.message}</TableCell>
                <TableCell align="center">
                  {log.count > 1 && (
                    <Chip label={`×${log.count}`} size="small" variant="outlined" />
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </AdminLayout>
  );
}