'use client';
import { useEffect, useState, useCallback } from 'react';
import { monitoringService } from '@/services/monitoring.service';

interface MetricLine {
  name: string;
  value: string;
  labels: string;
}

function parseMetrics(text: string): MetricLine[] {
  const lines = text.split('\n');
  const metrics: MetricLine[] = [];
  for (const line of lines) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('{')) continue;
    const match = trimmed.match(/([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(.+)\})?\s+(.+)/);
    if (match) {
      metrics.push({
        name: match[1],
        labels: match[3] ?? '',
        value: match[4] ?? '',
      });
    }
  }
  return metrics;
}

export default function MonitoringMetricsPage() {
  const [raw, setRaw] = useState<string>('');
  const [metrics, setMetrics] = useState<MetricLine[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');

  const fetchMetrics = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const text = await monitoringService.getMetrics();
      setRaw(text);
      setMetrics(parseMetrics(text));
    } catch (e: any) {
      setError(e?.message ?? 'Failed to fetch metrics');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchMetrics();
    const id = setInterval(fetchMetrics, 15000);
    return () => clearInterval(id);
  }, [fetchMetrics]);

  // Derive key stats from parsed metrics.
  const totalMetrics = metrics.length;
  const requestsTotal = metrics.find((m) => m.name === 'arb_http_requests_total')?.value;
  const errorsTotal = metrics.find((m) => m.name === 'arb_http_errors_total')?.value;
  const wsConnections = metrics.filter((m) => m.name === 'arb_websocket_connections')
    .reduce((sum, m) => sum + (parseFloat(m.value) || 0), 0);
  const found = metrics.filter((m) => m.labels.includes(search) ?? m.name.includes(search));

  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">Prometheus Metrics</h1>
          <p className="mt-1 text-sm text-white/50">Raw metrics exposed at <code className="rounded bg-white/5 px-1 py-0.5 text-[11px] font-mono text-indigo-300">GET /metrics</code></p>
        </div>
        <div className="flex items-center gap-3">
          <input
            type="text"
            placeholder="Filter metrics..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white placeholder-slate-500 focus:border-indigo-500 focus:outline-none"
          />
          <button onClick={fetchMetrics} 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>
      )}

      {/* Summary cards */}
      <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">Total Metrics</p>
          <p className="mt-1 font-mono text-2xl text-white">{totalMetrics}</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">HTTP Requests</p>
          <p className="mt-1 font-mono text-2xl text-emerald-400">{requestsTotal ?? '-'}</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">HTTP Errors</p>
          <p className="mt-1 font-mono text-2xl text-red-400">{errorsTotal ?? '-'}</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">WebSocket Connections</p>
          <p className="mt-1 font-mono text-2xl text-cyan-400">{wsConnections}</p>
        </div>
      </div>

      {/* Metrics table */}
      <div className="overflow-x-auto rounded-xl border border-white/5">
        <table className="w-full text-left text-xs">
          <thead className="border-b border-white/5 bg-white/[0.02]">
            <tr>
              <th className="px-4 py-3 text-slate-400">Metric</th>
              <th className="px-4 py-3 text-slate-400">Labels</th>
              <th className="px-4 py-3 text-slate-400">Value</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={3} className="px-4 py-8 text-center text-slate-500">Loading...</td></tr>
            ) : found.length === 0 ? (
              <tr><td colSpan={3} className="px-4 py-8 text-center text-slate-500">No metrics found</td></tr>
            ) : (
              found.slice(0, 200).map((m, i) => (
                <tr key={i} className="border-b border-white/5 hover:bg-white/[0.02]">
                  <td className="px-4 py-2 font-mono text-white">{m.name}</td>
                  <td className="px-4 py-2 font-mono text-slate-400 break-all">{m.labels}</td>
                  <td className="px-4 py-2 font-mono text-indigo-300">{m.value}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <details className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
        <summary className="cursor-pointer text-xs font-medium text-slate-300">View raw Prometheus output</summary>
        <pre className="mt-3 overflow-x-auto rounded-lg bg-black/40 p-4 text-[10px] leading-relaxed text-emerald-300 font-mono whitespace-pre-wrap">
          {raw.slice(0, 20000)}
        </pre>
      </details>
    </div>
  );
}
