"use client";

import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
import { Badge, Button, PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { StatTile } from "@/components/admin/common";
import { api } from "@/lib/api";
import { formatDateTime } from "@/lib/format";
import { useApi } from "@/lib/use-api";

interface Health {
  status: "ok" | "degraded";
  checked_at: string;
  database: { client: string; latency_ms: number };
  workers: { name: string; label: string; interval_seconds: number; state: "ok" | "late" | "never"; last_run_at: string | null; last_duration_ms: number | null; runs: number; last_error: string | null; last_error_at: string | null }[];
  queues: Record<string, number | string | null>;
  whatsapp: { connected: number; in_error: number; incoming_webhook_errors_24h: number; provider: string };
  integrations: { payments: { mode: string; configured: string }; email: { configured: boolean; host: string | null }; storage: { driver: string; ok: boolean; error: string | null }; encryption_key: boolean };
  process: { uptime_seconds: number; memory_mb: number; node: string; pid: number; environment: string };
}

const QUEUE_LABEL: Record<string, string> = {
  campaign_recipients_waiting: "Campaign messages waiting",
  flow_runs_due: "Flow steps due",
  webhook_deliveries_due: "Webhook deliveries due",
  webhook_deliveries_failed_24h: "Webhook deliveries failed (24 h)",
  webhook_endpoints_disabled: "Webhook endpoints switched off",
  emails_pending: "Emails waiting",
  emails_failed_24h: "Emails failed (24 h)",
  emails_not_configured_24h: "Emails not sent, SMTP off (24 h)",
  usage_unconfirmed_over_48h: "Charges unconfirmed > 48 h",
  payments_open_over_1h: "Payments open > 1 h",
  support_tickets_waiting: "Tickets needing a reply",
};
const STATE = { ok: { label: "Running", tone: "teal" as const }, late: { label: "Late", tone: "brick" as const }, never: { label: "Not run yet", tone: "neutral" as const } };
const uptime = (s: number) => (s > 86400 ? `${Math.floor(s / 86400)} d ${Math.floor((s % 86400) / 3600)} h` : s > 3600 ? `${Math.floor(s / 3600)} h ${Math.floor((s % 3600) / 60)} min` : `${Math.floor(s / 60)} min`);

export default function HealthPage() {
  const toast = useToast();
  const { data, reload, loading } = useApi<{ data: Health }>("/admin/health");
  const [checking, setChecking] = useState(false);
  useEffect(() => {
    const t = setInterval(reload, 30_000);
    return () => clearInterval(t);
  }, [reload]);
  async function checkEmail() {
    setChecking(true);
    try {
      const r = await api.post<{ data: { ok: boolean; error: string | null } }>("/admin/health/check-email");
      toast(r.data.ok ? "success" : "error", r.data.ok ? "SMTP connection and login work" : `Email check failed: ${r.data.error}`);
    } finally {
      setChecking(false);
    }
  }
  const h = data?.data;
  return (
    <>
      <PageHeader
        title="System health"
        description={h ? `Checked ${formatDateTime(h.checked_at)}. Refreshes every 30 seconds.` : "Database, background workers, queues and integrations."}
        actions={
          <Button icon={<RefreshCw className="size-4" />} loading={loading} onClick={reload}>
            Refresh
          </Button>
        }
      />
      {!h ? (
        <Skeleton className="h-96" />
      ) : (
        <>
          <div className={`mb-6 rounded-lg px-4 py-3 text-sm ${h.status === "ok" ? "bg-teal-soft text-teal" : "bg-brick-soft text-brick"}`}>{h.status === "ok" ? "All systems running." : "Something needs attention: see the late workers or failed checks below."}</div>
          <div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-4">
            <StatTile label="Database" value={`${h.database.latency_ms} ms`} sub={h.database.client} />
            <StatTile label="WhatsApp numbers" value={h.whatsapp.connected} sub={`${h.whatsapp.in_error} with errors, ${h.whatsapp.incoming_webhook_errors_24h} webhook errors (24 h)`} tone={h.whatsapp.in_error ? "brick" : undefined} />
            <StatTile label="API process" value={uptime(h.process.uptime_seconds)} sub={`${h.process.memory_mb} MB, Node ${h.process.node}, ${h.process.environment}`} />
            <StatTile label="Storage" value={h.integrations.storage.ok ? "Writable" : "Failing"} sub={h.integrations.storage.error ?? h.integrations.storage.driver} tone={h.integrations.storage.ok ? undefined : "brick"} />
          </div>
          <Panel className="mb-6">
            <h2 className="border-b border-line px-5 py-3 font-semibold">Background workers</h2>
            <ul className="divide-y divide-line">
              {h.workers.map((w) => (
                <li key={w.name} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-5 py-3 text-sm">
                  <span className="min-w-0 flex-1 basis-56">
                    <span className="font-medium">{w.label}</span>
                    <span className="block text-[13px] text-muted">
                      Every {w.interval_seconds < 60 ? `${w.interval_seconds} s` : `${Math.round(w.interval_seconds / 60)} min`}, {w.runs.toLocaleString("en-IN")} runs{w.last_duration_ms !== null ? `, last took ${w.last_duration_ms} ms` : ""}
                    </span>
                    {w.last_error && <span className="block text-[13px] text-brick">Last error {formatDateTime(w.last_error_at)}: {w.last_error}</span>}
                  </span>
                  <Badge tone={STATE[w.state].tone}>{STATE[w.state].label}</Badge>
                  <span className="w-40 text-right text-[13px] text-muted">{w.last_run_at ? formatDateTime(w.last_run_at) : "—"}</span>
                </li>
              ))}
            </ul>
          </Panel>
          <div className="grid gap-6 lg:grid-cols-2">
            <Panel>
              <h2 className="border-b border-line px-5 py-3 font-semibold">Queues</h2>
              <ul className="divide-y divide-line">
                {Object.entries(QUEUE_LABEL).map(([k, label]) => (
                  <li key={k} className="flex justify-between px-5 py-2.5 text-sm">
                    <span>{label}</span>
                    <span className="tabular">{Number(h.queues[k] ?? 0).toLocaleString("en-IN")}</span>
                  </li>
                ))}
                {h.queues.webhook_deliveries_oldest_due_at && (
                  <li className="px-5 py-2.5 text-[13px] text-muted">Oldest webhook delivery due since {formatDateTime(String(h.queues.webhook_deliveries_oldest_due_at))}</li>
                )}
              </ul>
            </Panel>
            <Panel>
              <h2 className="border-b border-line px-5 py-3 font-semibold">Integrations</h2>
              <ul className="divide-y divide-line text-sm">
                <li className="flex items-center justify-between px-5 py-2.5">
                  <span>Payments (Razorpay)</span>
                  <Badge tone={h.integrations.payments.mode === "simulation" ? "amber" : "teal"}>{h.integrations.payments.mode === "simulation" ? "Test mode" : "Live"}</Badge>
                </li>
                <li className="flex flex-wrap items-center justify-between gap-2 px-5 py-2.5">
                  <span>Email (SMTP){h.integrations.email.host ? `: ${h.integrations.email.host}` : ""}</span>
                  <span className="flex items-center gap-2">
                    <Badge tone={h.integrations.email.configured ? "teal" : "amber"}>{h.integrations.email.configured ? "Configured" : "Not configured"}</Badge>
                    {h.integrations.email.configured && (
                      <Button size="sm" loading={checking} onClick={checkEmail}>
                        Check login
                      </Button>
                    )}
                  </span>
                </li>
                <li className="flex items-center justify-between px-5 py-2.5">
                  <span>WhatsApp Cloud API</span>
                  <Badge tone={h.whatsapp.provider === "cloud" ? "teal" : "amber"}>{h.whatsapp.provider === "cloud" ? "Live" : "Simulation"}</Badge>
                </li>
                <li className="flex items-center justify-between px-5 py-2.5">
                  <span>Encryption key</span>
                  <Badge tone={h.integrations.encryption_key ? "teal" : "brick"}>{h.integrations.encryption_key ? "Set" : "Missing"}</Badge>
                </li>
              </ul>
            </Panel>
          </div>
        </>
      )}
    </>
  );
}
