'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  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);
      // API calls would go here
      // const response = await apiClient.get('/admin/health');

      // Using mock data for development
      setServices([
        {
          name: 'Backend API',
          status: 'healthy',
          responseTime: 45,
          uptime: 99.98,
          lastCheck: new Date().toISOString(),
        },
        {
          name: 'PostgreSQL Database',
          status: 'healthy',
          responseTime: 12,
          uptime: 99.99,
          lastCheck: new Date().toISOString(),
        },
        {
          name: 'Redis Cache',
          status: 'healthy',
          responseTime: 3,
          uptime: 100,
          lastCheck: new Date().toISOString(),
        },
        {
          name: 'MongoDB',
          status: 'healthy',
          responseTime: 18,
          uptime: 99.95,
          lastCheck: new Date().toISOString(),
        },
        {
          name: 'MinIO Storage',
          status: 'degraded',
          responseTime: 250,
          uptime: 98.5,
          lastCheck: new Date().toISOString(),
        },
        {
          name: 'WebSocket Server',
          status: 'healthy',
          responseTime: 8,
          uptime: 99.97,
          lastCheck: new Date().toISOString(),
        },
      ]);

      setMetrics([
        {
          name: 'CPU Usage',
          value: 45,
          max: 100,
          unit: '%',
          status: 'normal',
        },
        {
          name: 'Memory Usage',
          value: 3.2,
          max: 8,
          unit: 'GB',
          status: 'normal',
        },
        {
          name: 'Disk Usage',
          value: 42,
          max: 100,
          unit: 'GB',
          status: 'normal',
        },
        {
          name: 'Network I/O',
          value: 125,
          max: 1000,
          unit: 'Mbps',
          status: 'normal',
        },
        {
          name: 'Database Connections',
          value: 85,
          max: 100,
          unit: '',
          status: 'warning',
        },
        {
          name: 'Redis Memory',
          value: 450,
          max: 512,
          unit: 'MB',
          status: 'warning',
        },
      ]);

      setErrorLogs([
        {
          id: '1',
          timestamp: new Date(Date.now() - 5 * 60000).toISOString(),
          severity: 'warning',
          service: 'MinIO',
          message: 'High response time detected',
          count: 3,
        },
        {
          id: '2',
          timestamp: new Date(Date.now() - 15 * 60000).toISOString(),
          severity: 'error',
          service: 'Backend API',
          message: 'Rate limit exceeded for IP 192.168.1.105',
          count: 12,
        },
        {
          id: '3',
          timestamp: new Date(Date.now() - 30 * 60000).toISOString(),
          severity: 'info',
          service: 'Database',
          message: 'Automatic vacuum completed',
          count: 1,
        },
        {
          id: '4',
          timestamp: new Date(Date.now() - 45 * 60000).toISOString(),
          severity: 'warning',
          service: 'Redis',
          message: 'Memory usage above 85%',
          count: 2,
        },
        {
          id: '5',
          timestamp: new Date(Date.now() - 60 * 60000).toISOString(),
          severity: 'info',
          service: 'System',
          message: 'Daily backup completed successfully',
          count: 1,
        },
      ]);

      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>
      <Grid container spacing={2} sx={{ mb: 4 }}>
        {services.map((service) => (
          <Grid item xs={12} sm={6} md={4} key={service.name}>
            <Card>
              <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>
          </Grid>
        ))}
      </Grid>

      {/* System Metrics */}
      <Typography variant="h6" gutterBottom sx={{ mt: 4, mb: 2 }}>
        System Metrics
      </Typography>
      <Grid container spacing={3} sx={{ mb: 4 }}>
        {metrics.map((metric) => (
          <Grid item xs={12} sm={6} md={4} key={metric.name}>
            <Paper 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>
          </Grid>
        ))}
      </Grid>

      {/* 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>
  );
}