"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { apiGet } from "@/lib/api";
import type { NotificationClosureSnapshot } from "@/types";

type Props = {
  variant?: "full" | "compact";
};

function toneClasses(tone: "GOOD" | "WATCH" | "URGENT" | "INFO") {
  switch (tone) {
    case "GOOD":
      return "bg-emerald-50 text-emerald-700 border-emerald-100";
    case "WATCH":
      return "bg-amber-50 text-amber-700 border-amber-100";
    case "URGENT":
      return "bg-rose-50 text-rose-700 border-rose-100";
    default:
      return "bg-slate-50 text-slate-700 border-slate-100";
  }
}

export function NotificationClosureAudit({ variant = "full" }: Props) {
  const [snapshot, setSnapshot] = useState<NotificationClosureSnapshot | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    apiGet<{ snapshot: NotificationClosureSnapshot }>("/api/notifications/closure")
      .then((data) => {
        if (cancelled) return;
        setSnapshot(data.snapshot);
      })
      .catch((err: any) => {
        if (cancelled) return;
        setError(err?.message ?? "Failed to load notification closure summary");
      });

    return () => {
      cancelled = true;
    };
  }, []);

  if (error) {
    return (
      <section className="rounded-2xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-700">
        {error}
      </section>
    );
  }

  if (!snapshot) {
    return (
      <section className="rounded-2xl border border-slate-200 bg-white p-4 text-sm text-slate-500">
        Loading notification closure summary…
      </section>
    );
  }

  if (variant === "compact") {
    return (
      <section className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold ${toneClasses(snapshot.overallTone)}`}>
                {snapshot.overallLabel}
              </span>
              <span className="text-xs uppercase tracking-[0.2em] text-slate-400">Notification closure</span>
            </div>
            <h3 className="text-base font-semibold text-slate-900">Reminder coverage and escalation readiness</h3>
            <p className="max-w-3xl text-sm text-slate-600">{snapshot.summary}</p>
          </div>
          <div className="grid grid-cols-2 gap-2 text-sm lg:w-[360px]">
            {snapshot.metrics.slice(0, 4).map((metric) => (
              <div key={metric.key} className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
                <div className="text-xs uppercase tracking-[0.16em] text-slate-400">{metric.label}</div>
                <div className="mt-1 text-lg font-semibold text-slate-900">{metric.value}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="mt-4 flex flex-wrap gap-2">
          <Link href="/dashboard" className="inline-flex items-center rounded-full bg-slate-900 px-3 py-2 text-xs font-semibold text-white">
            Open CORI Briefing
          </Link>
          <Link href="/dispatch?report=queue-state&source=notification-closure" className="inline-flex items-center rounded-full border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700">
            Open queue follow-up
          </Link>
        </div>
      </section>
    );
  }

  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold ${toneClasses(snapshot.overallTone)}`}>
              {snapshot.overallLabel}
            </span>
            <span className="text-xs uppercase tracking-[0.2em] text-slate-400">v170 closure audit</span>
          </div>
          <h2 className="text-lg font-semibold text-slate-900">Notification closure summary</h2>
          <p className="max-w-3xl text-sm text-slate-600">{snapshot.summary}</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href="/dispatch?report=queue-state&source=notification-closure" className="inline-flex items-center rounded-full bg-slate-900 px-3 py-2 text-xs font-semibold text-white">
            Open dispatcher follow-up
          </Link>
          <Link href="/dispatch?unassigned=true&report=queue-state&source=notification-closure" className="inline-flex items-center rounded-full border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700">
            Open assignment pressure
          </Link>
        </div>
      </div>

      <div className="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        {snapshot.metrics.map((metric) => (
          <article key={metric.key} className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="flex items-center justify-between gap-2">
              <div className="text-xs uppercase tracking-[0.18em] text-slate-400">{metric.label}</div>
              <span className={`inline-flex rounded-full border px-2 py-0.5 text-[11px] font-semibold ${toneClasses(metric.tone)}`}>
                {metric.tone.toLowerCase()}
              </span>
            </div>
            <div className="mt-2 text-2xl font-semibold text-slate-900">{metric.value}</div>
            <p className="mt-1 text-xs leading-5 text-slate-500">{metric.helpText}</p>
          </article>
        ))}
      </div>

      <div className="mt-5 grid gap-5 xl:grid-cols-[1.15fr_0.85fr]">
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="flex items-center justify-between gap-3">
            <h3 className="text-sm font-semibold text-slate-900">Reminder lane coverage</h3>
            <span className="text-xs text-slate-500">Preferences + queue pressure</span>
          </div>
          <div className="mt-4 grid gap-3 md:grid-cols-2">
            {snapshot.lanes.map((lane) => (
              <article key={lane.key} className="rounded-2xl border border-white bg-white px-4 py-3">
                <div className="flex items-center justify-between gap-2">
                  <div className="text-sm font-semibold text-slate-900">{lane.label}</div>
                  <span className={`inline-flex rounded-full border px-2 py-0.5 text-[11px] font-semibold ${toneClasses(lane.tone)}`}>
                    {lane.state}
                  </span>
                </div>
                <p className="mt-2 text-sm leading-6 text-slate-600">{lane.body}</p>
              </article>
            ))}
          </div>
        </div>

        <div className="space-y-5">
          <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div className="flex items-center justify-between gap-3">
              <h3 className="text-sm font-semibold text-slate-900">Notification prompts</h3>
              <span className="text-xs text-slate-500">Action guidance</span>
            </div>
            <div className="mt-4 space-y-3">
              {snapshot.prompts.map((prompt) => (
                <article key={prompt.key} className="rounded-2xl border border-white bg-white px-4 py-3">
                  <div className="flex items-center justify-between gap-2">
                    <div className="text-sm font-semibold text-slate-900">{prompt.label}</div>
                    <span className={`inline-flex rounded-full border px-2 py-0.5 text-[11px] font-semibold ${toneClasses(prompt.tone)}`}>
                      {prompt.tone.toLowerCase()}
                    </span>
                  </div>
                  <p className="mt-2 text-sm leading-6 text-slate-600">{prompt.body}</p>
                </article>
              ))}
            </div>
          </div>

          <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div className="flex items-center justify-between gap-3">
              <h3 className="text-sm font-semibold text-slate-900">Recent delivery behavior</h3>
              <span className="text-xs text-slate-500">Last 10 outbound items</span>
            </div>
            <div className="mt-4 grid gap-3 sm:grid-cols-3">
              <div className="rounded-2xl border border-white bg-white px-4 py-3">
                <div className="text-xs uppercase tracking-[0.16em] text-slate-400">Sent</div>
                <div className="mt-2 text-xl font-semibold text-slate-900">{snapshot.logs.sent}</div>
              </div>
              <div className="rounded-2xl border border-white bg-white px-4 py-3">
                <div className="text-xs uppercase tracking-[0.16em] text-slate-400">Failed</div>
                <div className="mt-2 text-xl font-semibold text-slate-900">{snapshot.logs.failed}</div>
              </div>
              <div className="rounded-2xl border border-white bg-white px-4 py-3">
                <div className="text-xs uppercase tracking-[0.16em] text-slate-400">Skipped / pending</div>
                <div className="mt-2 text-xl font-semibold text-slate-900">{snapshot.logs.skippedOrPending}</div>
              </div>
            </div>
            <p className="mt-3 text-sm text-slate-600">{snapshot.logs.note}</p>
          </div>
        </div>
      </div>
    </section>
  );
}
