'use client';

import { useEffect, useState } from 'react';

interface Check {
  name: string;
  status: 'pass' | 'fail';
  message?: string;
  latencyMs?: number;
}

interface HealthResponse {
  status: string;
  service: string;
  timestamp: string;
  checks: Check[];
}

export default function HealthPage() {
  const [data, setData] = useState<HealthResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/health')
      .then(res => res.json())
      .then(json => setData(json))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div style={{ fontFamily: 'system-ui', padding: 40 }}>
        <p>Checking health…</p>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ fontFamily: 'system-ui', padding: 40 }}>
        <h1 style={{ color: 'hsl(var(--destructive))' }}>Health Check Failed</h1>
        <p>{error}</p>
      </div>
    );
  }

  const overall = data?.status === 'ok';

  return (
    <div style={{ fontFamily: 'system-ui', padding: 40, maxWidth: 600 }}>
      <h1 style={{ marginBottom: 4 }}>
        {overall ? '✅' : '⚠️'} {data?.service}
      </h1>
      <p style={{ color: 'hsl(var(--muted-foreground))', marginTop: 0 }}>{data?.timestamp}</p>
      <p
        style={{
          fontSize: 18,
          fontWeight: 600,
          color: overall ? 'hsl(var(--chart-2))' : 'hsl(var(--destructive))',
        }}
      >
        Status: {data?.status}
      </p>
      <table
        style={{
          width: '100%',
          borderCollapse: 'collapse',
          marginTop: 16,
        }}
      >
        <thead>
          <tr style={{ borderBottom: '2px solid hsl(var(--border))' }}>
            <th style={{ textAlign: 'left', padding: 8 }}>Check</th>
            <th style={{ textAlign: 'left', padding: 8 }}>Status</th>
            <th style={{ textAlign: 'left', padding: 8 }}>Details</th>
          </tr>
        </thead>
        <tbody>
          {data?.checks.map(check => (
            <tr key={check.name} style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <td style={{ padding: 8, fontWeight: 500 }}>{check.name}</td>
              <td style={{ padding: 8 }}>{check.status === 'pass' ? '✅ pass' : '❌ fail'}</td>
              <td style={{ padding: 8, color: 'hsl(var(--muted-foreground))', fontSize: 14 }}>
                {check.message}
                {check.latencyMs != null && ` (${check.latencyMs}ms)`}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
