'use client';
import { useEffect, useState, useCallback } from 'react';
import { monitoringService } from '@/services/monitoring.service';
import type { Alert, AlertRule } from '@/types/monitoring.types';

const SEVERITY_STYLES: Record<string, string> = {
  info: 'bg-sky-500/15 text-sky-400 border-sky-500/20',
  warning: 'bg-amber-500/15 text-amber-400 border-amber-500/20',
  critical: 'bg-red-500/15 text-red-400 border-red-500/20',
};

export default function MonitoringAlertsPage() {
  const [active, setActive] = useState<Alert[]>([]);
  const [history, setHistory] = useState<Alert[]>([]);
  const [rules, setRules] = useState<AlertRule[]>([]);
  const [loading, setLoading] = useState(true);
  const [evaluating, setEvaluating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<'active' | 'history' | 'rules'>('active');

  const fetchAll = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [activeRes, historyRes, rulesRes] = await Promise.all([
        monitoringService.getActiveAlerts(),
        monitoringService.getAlertHistory(50),
        monitoringService.getAlertRules(),
      ]);
      setActive(activeRes);
      setHistory(historyRes);
      setRules(rulesRes);
    } catch (e: any) {
      setError(e?.message ?? 'Failed to fetch alerts');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAll();
    const id = setInterval(fetchAll, 30000);
    return () => clearInterval(id);
  }, [fetchAll]);

  const handleEvaluate = async () => {
    setEvaluating(true);
    try {
      await monitoringService.evaluateAlerts();
      await fetchAll();
    } catch (e: any) {
      setError(e?.message ?? 'Failed to evaluate alerts');
    } finally {
      setEvaluating(false);
    }
  };

  const severityClass = (s: string) => SEVERITY_STYLES[s] ?? SEVERITY_STYLES.info;
  const activeCritical = active.filter((a) => !a.resolved && a.severity === 'critical').length;

  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">Monitoring Alerts</h1>
          <p className="mt-1 text-sm text-white/50">Active alerts, history, and configured rules</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={handleEvaluate}
            disabled={evaluating}
            className="rounded-lg bg-amber-500/15 px-3 py-2 text-xs text-amber-300 hover:bg-amber-500/25 disabled:opacity-50 transition-colors"
          >
            {evaluating ? 'Evaluating...' : 'Evaluate Now'}
          </button>
          <button onClick={fetchAll} 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>
      )}

      {/* Active alert summary */}
      <div className="grid grid-cols-3 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">Active</p>
          <p className="mt-1 font-mono text-2xl text-white">{active.filter((a) => !a.resolved).length}</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">Critical</p>
          <p className="mt-1 font-mono text-2xl text-red-400">{activeCritical}</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">Rules</p>
          <p className="mt-1 font-mono text-2xl text-white">{rules.length}</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-4 border-b border-white/10">
        {(['active', 'history', 'rules'] as const).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`pb-2 text-sm font-medium capitalize ${tab === t ? 'text-white border-b-2 border-indigo-400' : 'text-slate-500 hover:text-slate-300'}`}
          >
            {t}
          </button>
        ))}
      </div>

      <div className="overflow-x-auto rounded-xl border border-white/5">
        {loading ? (
          <div className="p-8 text-center text-sm text-slate-500">Loading...</div>
        ) : tab === 'active' ? (
          <AlertTable alerts={active.filter((a) => !a.resolved)} severityClass={severityClass} emptyLabel="No active alerts" />
        ) : tab === 'history' ? (
          <AlertTable alerts={history} severityClass={severityClass} emptyLabel="No alert history yet" />
        ) : (
          <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">Rule</th>
                <th className="px-4 py-3 text-slate-400">Severity</th>
                <th className="px-4 py-3 text-slate-400">Description</th>
              </tr>
            </thead>
            <tbody>
              {rules.map((r) => (
                <tr key={r.id} className="border-b border-white/5 hover:bg-white/[0.02]">
                  <td className="px-4 py-3 font-mono text-white">{r.name}</td>
                  <td className="px-4 py-3">
                    <span className={`rounded-lg border px-2 py-0.5 text-[10px] font-mono uppercase ${severityClass(r.severity)}`}>{r.severity}</span>
                  </td>
                  <td className="px-4 py-3 text-slate-400">{r.description}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function AlertTable({ alerts, severityClass, emptyLabel }: { alerts: Alert[]; severityClass: (s: string) => string; emptyLabel: string }) {
  if (alerts.length === 0) {
    return <div className="p-8 text-center text-sm text-slate-500">{emptyLabel}</div>;
  }
  return (
    <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">Alert</th>
          <th className="px-4 py-3 text-slate-400">Severity</th>
          <th className="px-4 py-3 text-slate-400">Value</th>
          <th className="px-4 py-3 text-slate-400">Triggered</th>
          <th className="px-4 py-3 text-slate-400">Status</th>
        </tr>
      </thead>
      <tbody>
        {alerts.map((a) => (
          <tr key={a.id} className="border-b border-white/5 hover:bg-white/[0.02]">
            <td className="px-4 py-3">
              <p className="font-medium text-white">{a.name}</p>
              <p className="text-[10px] text-slate-500">{a.description}</p>
            </td>
            <td className="px-4 py-3">
              <span className={`rounded-lg border px-2 py-0.5 text-[10px] font-mono uppercase ${severityClass(a.severity)}`}>{a.severity}</span>
            </td>
            <td className="px-4 py-3 font-mono text-slate-300">{a.value}</td>
            <td className="px-4 py-3 text-slate-400 whitespace-nowrap">{new Date(a.triggeredAt).toLocaleString()}</td>
            <td className="px-4 py-3">
              <span className={`rounded-lg border px-2 py-0.5 text-[10px] font-mono uppercase ${a.resolved ? 'bg-emerald-500/15 text-emerald-400 border-emerald-500/20' : 'bg-amber-500/15 text-amber-400 border-amber-500/20'}`}>
                {a.resolved ? 'Resolved' : 'Active'}
              </span>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
