'use client';
import { useEffect, useState, useCallback } from 'react';
import { monitoringService } from '@/services/monitoring.service';
import type { HealthResponse, HealthComponent } from '@/types/monitoring.types';

const STATUS_STYLES: Record<string, string> = {
  ok: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/20',
  error: 'bg-red-500/15 text-red-400 border-red-500/20',
  'not-implemented': 'bg-amber-500/15 text-amber-400 border-amber-500/20',
  'not-ready': 'bg-amber-500/15 text-amber-400 border-amber-500/20',
  unknown: 'bg-slate-500/15 text-slate-400 border-slate-500/20',
};

const STATUS_DOT: Record<string, string> = {
  ok: 'bg-emerald-400',
  error: 'bg-red-400',
  'not-implemented': 'bg-amber-400',
  'not-ready': 'bg-amber-400',
  unknown: 'bg-slate-400',
};

function ComponentCard({ name, comp }: { name: string; comp: HealthComponent }) {
  const style = STATUS_STYLES[comp.status] ?? STATUS_STYLES.unknown;
  const dot = STATUS_DOT[comp.status] ?? STATUS_DOT.unknown;
  return (
    <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
      <div className="flex items-center justify-between mb-1">
        <span className="text-sm font-medium text-white">{name}</span>
        <span className={`h-2 w-2 rounded-full ${dot} animate-pulse`} />
      </div>
      <div className="flex items-center gap-2">
        <span className={`rounded-lg border px-2 py-0.5 text-[10px] font-mono uppercase ${style}`}>
          {comp.status}
        </span>
        {comp.latencyMs !== undefined && (
          <span className="text-[10px] font-mono text-slate-500">{comp.latencyMs}ms</span>
        )}
      </div>
      {comp.message && <p className="mt-2 text-[11px] text-slate-500 break-words">{comp.message}</p>}
    </div>
  );
}

export default function MonitoringHealthPage() {
  const [health, setHealth] = useState<HealthResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchHealth = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await monitoringService.getHealth();
      setHealth(res);
    } catch (e: any) {
      setError(e?.message ?? 'Failed to fetch health');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchHealth();
    const id = setInterval(fetchHealth, 15000);
    return () => clearInterval(id);
  }, [fetchHealth]);

  const overall = health?.status;

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">System Health</h1>
          <p className="mt-1 text-sm text-white/50">Application, database, WebSocket, notification &amp; auth status</p>
        </div>
        <div className="flex items-center gap-3">
          {overall && (
            <span className={`rounded-lg border px-3 py-1.5 text-xs font-mono uppercase ${STATUS_STYLES[overall]}`}>
              {overall}
            </span>
          )}
          <button onClick={fetchHealth} className="rounded-lg bg-white/10 px-3 py-2 text-xs text-white/70 hover:bg-white/20 transition-colors">
            Refresh
          </button>
        </div>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-300">
          {error}
        </div>
      )}

      {loading && !health ? (
        <div className="animate-pulse space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-24 rounded-xl bg-white/[0.03]" />
          ))}
        </div>
      ) : health ? (
        <div className="space-y-6">
          {/* Metadata */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-3">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Application</p>
              <p className="mt-1 font-mono text-sm text-white truncate">{health.application}</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-3">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Version</p>
              <p className="mt-1 font-mono text-sm text-white">{health.version}</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-3">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Environment</p>
              <p className="mt-1 font-mono text-sm text-white">{health.environment}</p>
            </div>
            <div className="rounded-xl border border-white/5 bg-white/[0.02] p-3">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Uptime</p>
              <p className="mt-1 font-mono text-sm text-white">{health.uptimeSeconds}s</p>
            </div>
          </div>

          {/* Components */}
          <div>
            <h3 className="mb-3 text-sm font-medium text-white">Components</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
              <ComponentCard name="Application" comp={health.components.application} />
              <ComponentCard name="Database" comp={health.components.database} />
              <ComponentCard name="WebSocket" comp={health.components.websocket} />
              <ComponentCard name="Notifications" comp={health.components.notifications} />
              <ComponentCard name="Authentication" comp={health.components.authentication} />
            </div>
          </div>

          <p className="text-[10px] font-mono text-slate-600">Last check: {new Date(health.timestamp).toLocaleString()}</p>
        </div>
      ) : null}
    </div>
  );
}
