'use client';

import { useQuery } from '@tanstack/react-query';
import {
  Activity,
  Database,
  Info,
  RefreshCw,
  CheckCircle2,
  XCircle,
  Clock,
  Server,
  Cpu,
  Globe,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import axios from 'axios';

const API_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000';

// Dedicated bare client — no auth token, no 401 redirect interceptor.
// Health probes are public. We unwrap the { success, data } envelope explicitly.
const healthClient = axios.create({ baseURL: API_URL });

async function fetchHealth(path: string) {
  const res = await healthClient.get<{ success: boolean; data: any }>(path);
  return res.data?.data ?? res.data;
}

function StatusDot({ ok }: { ok: boolean | null }) {
  if (ok === null)
    return <span className="inline-block h-2.5 w-2.5 rounded-full bg-muted animate-pulse" />;
  return ok ? (
    <span className="inline-block h-2.5 w-2.5 rounded-full bg-emerald-500 shadow-[0_0_6px_2px_rgba(16,185,129,0.4)]" />
  ) : (
    <span className="inline-block h-2.5 w-2.5 rounded-full bg-red-500 shadow-[0_0_6px_2px_rgba(239,68,68,0.4)]" />
  );
}

function StatusBadge({ ok }: { ok: boolean | null }) {
  if (ok === null)
    return <span className="edr-badge bg-muted text-muted-foreground">Checking…</span>;
  return ok ? (
    <span className="edr-badge edr-badge-success">Healthy</span>
  ) : (
    <span className="edr-badge bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400">Degraded</span>
  );
}

function MetricRow({ label, value, icon: Icon }: { label: string; value: string; icon: any }) {
  return (
    <div className="flex items-center justify-between py-2.5 border-b border-border last:border-0">
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <Icon className="h-4 w-4 shrink-0" />
        {label}
      </div>
      <span className="text-sm font-medium text-foreground">{value}</span>
    </div>
  );
}

export default function HealthPage() {
  const { data: liveness, isFetching: l1, dataUpdatedAt: t1, refetch: r1, error: e1 } = useQuery({
    queryKey: ['health-liveness'],
    queryFn: () => fetchHealth('/health'),
    refetchInterval: 30_000,
    retry: 1,
  });

  const { data: readiness, isFetching: l2, dataUpdatedAt: t2, refetch: r2, error: e2 } = useQuery({
    queryKey: ['health-readiness'],
    queryFn: () => fetchHealth('/health/ready'),
    refetchInterval: 30_000,
    retry: 1,
  });

  const { data: info, isFetching: l3, dataUpdatedAt: t3, refetch: r3 } = useQuery({
    queryKey: ['health-info'],
    queryFn: () => fetchHealth('/health/info'),
    refetchInterval: 60_000,
    retry: 1,
  });

  const livenessOk  = e1 ? false : liveness  ? liveness.status  === 'ok' : null;
  const readinessOk = e2 ? false : readiness ? readiness.status === 'ok' : null;
  const dbOk        = readiness?.checks?.database?.status === 'ok';
  const overallOk   =
    livenessOk === null || readinessOk === null ? null : livenessOk && readinessOk;

  const fmt = (ms: number) => new Date(ms).toLocaleTimeString();
  const fmtUptime = (s: number) => {
    const h   = Math.floor(s / 3600);
    const m   = Math.floor((s % 3600) / 60);
    const sec = s % 60;
    return `${h}h ${m}m ${sec}s`;
  };

  function refetchAll() { r1(); r2(); r3(); }

  return (
    <div className="space-y-6 animate-fade-up">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">System Health</h1>
          <p className="text-muted-foreground text-sm mt-0.5">
            Live status of the EDR Passenger API — auto-refreshes every 30 s
          </p>
        </div>
        <button
          onClick={refetchAll}
          className={cn(
            'btn btn-secondary flex items-center gap-2 text-sm',
            (l1 || l2 || l3) && 'opacity-60 cursor-not-allowed',
          )}
          disabled={l1 || l2 || l3}
        >
          <RefreshCw className={cn('h-4 w-4', (l1 || l2 || l3) && 'animate-spin')} />
          Refresh
        </button>
      </div>

      {/* Overall banner */}
      <div
        className={cn(
          'flex items-center gap-4 rounded-xl border px-6 py-4 transition-colors',
          overallOk === null
            ? 'border-border bg-muted/40'
            : overallOk
            ? 'border-emerald-200 bg-emerald-50 dark:border-emerald-800/40 dark:bg-emerald-900/10'
            : 'border-red-200 bg-red-50 dark:border-red-800/40 dark:bg-red-900/10',
        )}
      >
        {overallOk === null ? (
          <Activity className="h-7 w-7 text-muted-foreground animate-pulse" />
        ) : overallOk ? (
          <CheckCircle2 className="h-7 w-7 text-emerald-600 dark:text-emerald-400" />
        ) : (
          <XCircle className="h-7 w-7 text-red-600 dark:text-red-400" />
        )}
        <div>
          <p className={cn(
            'font-semibold text-base',
            overallOk === null
              ? 'text-muted-foreground'
              : overallOk
              ? 'text-emerald-700 dark:text-emerald-300'
              : 'text-red-700 dark:text-red-300',
          )}>
            {overallOk === null
              ? 'Checking system status…'
              : overallOk
              ? 'All systems operational'
              : 'Service degraded'}
          </p>
          <p className="text-xs text-muted-foreground mt-0.5">
            EDR Passenger API · {API_URL}
          </p>
        </div>
      </div>

      {/* Probe cards */}
      <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
        {/* Liveness */}
        <div className="card space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="rounded-lg bg-green-100 p-2 dark:bg-green-900/30">
                <Activity className="h-5 w-5 text-green-700 dark:text-green-400" />
              </div>
              <div>
                <p className="font-semibold text-foreground text-sm">Liveness</p>
                <p className="text-xs text-muted-foreground">GET /health</p>
              </div>
            </div>
            <StatusDot ok={livenessOk} />
          </div>
          <div className="flex items-center justify-between">
            <StatusBadge ok={livenessOk} />
            {t1 > 0 && (
              <span className="flex items-center gap-1 text-xs text-muted-foreground">
                <Clock className="h-3 w-3" /> {fmt(t1)}
              </span>
            )}
          </div>
          {e1 && (
            <p className="text-xs text-red-600 dark:text-red-400 font-mono break-all">
              {(e1 as any)?.message ?? 'Request failed'}
            </p>
          )}
          <p className="text-xs text-muted-foreground leading-relaxed">
            Confirms the process is alive and accepting connections. Checked every 30 s.
          </p>
        </div>

        {/* Readiness */}
        <div className="card space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="rounded-lg bg-blue-100 p-2 dark:bg-blue-900/30">
                <Database className="h-5 w-5 text-blue-700 dark:text-blue-400" />
              </div>
              <div>
                <p className="font-semibold text-foreground text-sm">Readiness</p>
                <p className="text-xs text-muted-foreground">GET /health/ready</p>
              </div>
            </div>
            <StatusDot ok={readinessOk} />
          </div>
          <div className="flex items-center justify-between">
            <StatusBadge ok={readinessOk} />
            {t2 > 0 && (
              <span className="flex items-center gap-1 text-xs text-muted-foreground">
                <Clock className="h-3 w-3" /> {fmt(t2)}
              </span>
            )}
          </div>
          {e2 && (
            <p className="text-xs text-red-600 dark:text-red-400 font-mono break-all">
              {(e2 as any)?.message ?? 'Request failed'}
            </p>
          )}
          <p className="text-xs text-muted-foreground leading-relaxed">
            Runs a live database ping. Latency:{' '}
            <span className="font-medium text-foreground">
              {readiness?.checks?.database?.latencyMs != null
                ? `${readiness.checks.database.latencyMs} ms`
                : '—'}
            </span>
          </p>
        </div>

        {/* App Info */}
        <div className="card space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="rounded-lg bg-purple-100 p-2 dark:bg-purple-900/30">
                <Info className="h-5 w-5 text-purple-700 dark:text-purple-400" />
              </div>
              <div>
                <p className="font-semibold text-foreground text-sm">App Info</p>
                <p className="text-xs text-muted-foreground">GET /health/info</p>
              </div>
            </div>
            <StatusDot ok={info ? true : null} />
          </div>
          <div className="flex items-center justify-between">
            <StatusBadge ok={info ? true : null} />
            {t3 > 0 && (
              <span className="flex items-center gap-1 text-xs text-muted-foreground">
                <Clock className="h-3 w-3" /> {fmt(t3)}
              </span>
            )}
          </div>
          <p className="text-xs text-muted-foreground leading-relaxed">
            Version, environment, and uptime. Refreshed every 60 s.
          </p>
        </div>
      </div>

      {/* Detailed panels */}
      <div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
        {/* Database detail */}
        <div className="card space-y-1">
          <div className="flex items-center gap-2 mb-4">
            <Database className="h-5 w-5 text-muted-foreground" />
            <h2 className="font-semibold text-foreground">Database</h2>
            <div className="ml-auto">
              <StatusBadge ok={readiness ? dbOk : null} />
            </div>
          </div>
          <MetricRow
            label="Status"
            value={readiness?.checks?.database?.status ?? '—'}
            icon={CheckCircle2}
          />
          <MetricRow
            label="Latency"
            value={
              readiness?.checks?.database?.latencyMs != null
                ? `${readiness.checks.database.latencyMs} ms`
                : '—'
            }
            icon={Activity}
          />
          {readiness?.checks?.database?.error && (
            <div className="mt-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/40 px-4 py-3">
              <p className="text-xs text-red-700 dark:text-red-300 font-mono break-all">
                {readiness.checks.database.error}
              </p>
            </div>
          )}
        </div>

        {/* App info detail */}
        <div className="card space-y-1">
          <div className="flex items-center gap-2 mb-4">
            <Server className="h-5 w-5 text-muted-foreground" />
            <h2 className="font-semibold text-foreground">Application</h2>
          </div>
          <MetricRow label="Name"        value={info?.name        ?? '—'} icon={Server} />
          <MetricRow label="Version"     value={info?.version     ?? '—'} icon={Info}   />
          <MetricRow label="Environment" value={info?.environment ?? '—'} icon={Globe}  />
          <MetricRow
            label="Uptime"
            value={info?.uptimeSeconds != null ? fmtUptime(info.uptimeSeconds) : '—'}
            icon={Cpu}
          />
          <MetricRow
            label="Last checked"
            value={t3 > 0 ? new Date(t3).toLocaleString() : '—'}
            icon={Clock}
          />
        </div>
      </div>

      {/* Rate limits reference */}
      <div className="card">
        <div className="flex items-center gap-2 mb-4">
          <Activity className="h-5 w-5 text-muted-foreground" />
          <h2 className="font-semibold text-foreground">Rate Limits</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left text-muted-foreground">
                <th className="pb-2 pr-6 font-medium">Tier</th>
                <th className="pb-2 pr-6 font-medium">Limit</th>
                <th className="pb-2 font-medium">Applied to</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {[
                { tier: 'auth',    limit: '5 req / min',   scope: '/auth, /fayda/verification' },
                { tier: 'strict',  limit: '20 req / min',  scope: '/bookings, /passengers, /payments, /wallet' },
                { tier: 'default', limit: '100 req / min', scope: 'All other endpoints' },
                { tier: 'exempt',  limit: '—',             scope: '/health/*, /internal/payments/*, payment webhooks' },
              ].map((row) => (
                <tr key={row.tier}>
                  <td className="py-2.5 pr-6">
                    <span className={cn(
                      'edr-badge',
                      row.tier === 'auth'    && 'edr-badge-danger',
                      row.tier === 'strict'  && 'edr-badge-warning',
                      row.tier === 'default' && 'edr-badge-success',
                      row.tier === 'exempt'  && 'edr-badge-info',
                    )}>
                      {row.tier}
                    </span>
                  </td>
                  <td className="py-2.5 pr-6 font-mono text-foreground">{row.limit}</td>
                  <td className="py-2.5 text-muted-foreground">{row.scope}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
