"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { apiPost } from "@/lib/api";
import type { AppNotification, AppNotificationSnapshot } from "@/types";

type StateResponse = { snapshot: AppNotificationSnapshot };
type NotificationStateAction = "MARK_READ" | "MARK_UNREAD" | "DISMISS" | "RESTORE" | "MARK_ALL_READ";

function toneClass(tone: AppNotification["tone"]) {
  if (tone === "URGENT") return "border-rose-200 bg-rose-50 text-rose-700";
  if (tone === "WATCH") return "border-amber-200 bg-amber-50 text-amber-700";
  if (tone === "GOOD") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

function readLabel(item: AppNotification) {
  return item.isRead ? "Read" : "Unread";
}

export function SimpleNotificationList({ snapshot: initialSnapshot }: { snapshot: AppNotificationSnapshot }) {
  const [snapshot, setSnapshot] = useState(initialSnapshot);
  const [busyKey, setBusyKey] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [showHidden, setShowHidden] = useState(false);

  const activeItemIds = useMemo(() => snapshot.items.map((item) => item.id), [snapshot.items]);

  async function updateState(action: NotificationStateAction, notificationId?: string) {
    setBusyKey(notificationId ?? action);
    setNotice(null);
    try {
      const response = await apiPost<StateResponse>("/api/app-notifications/state", { action, notificationId });
      setSnapshot(response.snapshot);
      window.dispatchEvent(new CustomEvent("dispatchspot:notifications-updated", { detail: response.snapshot }));
      if (action === "MARK_ALL_READ") setNotice("All visible alerts are marked as read.");
      if (action === "DISMISS") setNotice("Alert hidden from your active list.");
      if (action === "RESTORE") setNotice("Alert restored to your active list.");
      if (action === "MARK_READ") setNotice("Alert marked as read.");
      if (action === "MARK_UNREAD") setNotice("Alert marked as unread.");
    } catch (error: any) {
      setNotice(error?.message ?? "Alert could not be updated.");
    } finally {
      setBusyKey(null);
    }
  }

  return (
    <div className="space-y-6">
      {!snapshot.preferences.inApp ? (
        <div className="rounded-3xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600">
          In-app alert badges are off for this user. This page still shows the alerts so they can be reviewed when needed.
        </div>
      ) : null}

      <section className="grid gap-4 md:grid-cols-4">
        <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Needs attention</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{snapshot.attentionCount}</div>
          <p className="mt-2 text-sm text-slate-500">Active alerts CORI thinks should be checked soon.</p>
        </div>
        <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Unread</div>
          <div className="mt-2 text-3xl font-semibold text-blue-700">{snapshot.unreadCount}</div>
          <p className="mt-2 text-sm text-slate-500">Unread active alerts shown in the top-bar badge.</p>
        </div>
        <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Urgent</div>
          <div className="mt-2 text-3xl font-semibold text-rose-700">{snapshot.urgentCount}</div>
          <p className="mt-2 text-sm text-slate-500">Late, missing, or money-related work that may need action now.</p>
        </div>
        <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Hidden</div>
          <div className="mt-2 text-3xl font-semibold text-slate-600">{snapshot.dismissedCount}</div>
          <p className="mt-2 text-sm text-slate-500">Alerts you dismissed from your active list.</p>
        </div>
      </section>

      {notice ? (
        <div className="rounded-3xl border border-blue-200 bg-blue-50 p-4 text-sm leading-6 text-blue-800">{notice}</div>
      ) : null}

      <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
          <div>
            <h2 className="text-lg font-semibold text-slate-950">Today’s alerts</h2>
            <p className="mt-1 text-sm text-slate-500">Read, reopen, or hide simple alerts from loads, paperwork, billing records, and tasks.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            {activeItemIds.length ? (
              <button
                type="button"
                onClick={() => updateState("MARK_ALL_READ")}
                disabled={busyKey === "MARK_ALL_READ" || snapshot.unreadCount === 0}
                className="rounded-2xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:text-slate-400"
              >
                Mark all read
              </button>
            ) : null}
            <Link href="/dashboard" className="rounded-2xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">
              Open CORI Briefing
            </Link>
          </div>
        </div>

        {snapshot.items.length ? (
          <div className="mt-5 space-y-3">
            {snapshot.items.map((item) => (
              <div key={item.id} className={`rounded-3xl border p-4 ${item.isRead ? "border-slate-200 bg-white" : "border-blue-200 bg-blue-50/50"}`}>
                <div className="flex flex-col justify-between gap-3 lg:flex-row lg:items-start">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold ${toneClass(item.tone)}`}>{item.sourceLabel}</span>
                      <span className="rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[11px] font-semibold text-slate-500">{readLabel(item)}</span>
                      {!item.isRead ? <span className="h-2.5 w-2.5 rounded-full bg-blue-600" aria-label="Unread alert" /> : null}
                    </div>
                    <h3 className="mt-3 text-base font-semibold text-slate-950">{item.title}</h3>
                    <p className="mt-1 text-sm leading-6 text-slate-600">{item.message}</p>
                  </div>
                  <div className="flex shrink-0 flex-wrap gap-2 lg:justify-end">
                    <Link href={item.href} className="rounded-2xl bg-slate-900 px-4 py-2 text-center text-sm font-semibold text-white">
                      {item.primaryActionLabel}
                    </Link>
                    <button
                      type="button"
                      onClick={() => updateState(item.isRead ? "MARK_UNREAD" : "MARK_READ", item.id)}
                      disabled={busyKey === item.id}
                      className="rounded-2xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:cursor-wait disabled:text-slate-400"
                    >
                      {item.isRead ? "Mark unread" : "Mark read"}
                    </button>
                    <button
                      type="button"
                      onClick={() => updateState("DISMISS", item.id)}
                      disabled={busyKey === item.id}
                      className="rounded-2xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-500 disabled:cursor-wait disabled:text-slate-400"
                    >
                      Hide
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="mt-5 rounded-3xl border border-emerald-200 bg-emerald-50 p-5">
            <h3 className="text-base font-semibold text-emerald-800">{snapshot.emptyState?.title ?? "No urgent alerts right now"}</h3>
            <p className="mt-1 text-sm text-emerald-700">{snapshot.emptyState?.message ?? "Nothing needs attention from the current records."}</p>
          </div>
        )}
      </section>

      {snapshot.dismissedCount ? (
        <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
            <div>
              <h2 className="text-lg font-semibold text-slate-950">Hidden alerts</h2>
              <p className="mt-1 text-sm text-slate-500">Hidden alerts stay out of your active list, but you can show them again.</p>
            </div>
            <button
              type="button"
              onClick={() => setShowHidden((value) => !value)}
              className="rounded-2xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
            >
              {showHidden ? "Hide list" : "Show hidden"}
            </button>
          </div>

          {showHidden ? (
            <div className="mt-5 space-y-3">
              {snapshot.dismissedItems.map((item) => (
                <div key={item.id} className="rounded-3xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex flex-col justify-between gap-3 lg:flex-row lg:items-start">
                    <div>
                      <div className="flex flex-wrap items-center gap-2">
                        <span className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold ${toneClass(item.tone)}`}>{item.sourceLabel}</span>
                        <span className="rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[11px] font-semibold text-slate-500">Hidden</span>
                      </div>
                      <h3 className="mt-3 text-base font-semibold text-slate-950">{item.title}</h3>
                      <p className="mt-1 text-sm leading-6 text-slate-600">{item.message}</p>
                    </div>
                    <button
                      type="button"
                      onClick={() => updateState("RESTORE", item.id)}
                      disabled={busyKey === item.id}
                      className="shrink-0 rounded-2xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:cursor-wait disabled:text-slate-400"
                    >
                      Show again
                    </button>
                  </div>
                </div>
              ))}
              {snapshot.dismissedCount > snapshot.dismissedItems.length ? (
                <p className="text-sm text-slate-500">Only the most recent hidden alerts are shown here.</p>
              ) : null}
            </div>
          ) : null}
        </section>
      ) : null}
    </div>
  );
}
