"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Bell } from "lucide-react";

type ToastItem = {
  id: number;
  message: string;
  ok: boolean;
  kind: "api" | "notification";
  title: string;
  body: string;
  href: string;
};

export const API_TOAST_EVENT = "ar-api-toast";

export default function ApiToast() {
  const [items, setItems] = useState<ToastItem[]>([]);

  useEffect(() => {
    const onToast = (event: Event) => {
      const detail = (event as CustomEvent<{ message?: string; ok?: boolean; kind?: string; title?: string; body?: string; href?: string }>).detail;
      const kind = detail?.kind === "notification" ? "notification" : "api";
      const title = detail?.title?.trim() || "";
      const body = detail?.body?.trim() || "";
      const href = detail?.href?.trim() || "";
      const message = detail?.message?.trim() || [title, body].filter(Boolean).join(" — ");
      if (!message && !title && !body) return;
      const id = Date.now() + Math.random();
      setItems((current) => [...current, { id, message, ok: Boolean(detail?.ok), kind, title, body, href }]);
      window.setTimeout(() => {
        setItems((current) => current.filter((item) => item.id !== id));
      }, kind === "notification" ? 6000 : 4000);
    };
    window.addEventListener(API_TOAST_EVENT, onToast);
    return () => window.removeEventListener(API_TOAST_EVENT, onToast);
  }, []);

  const notices = items.filter((item) => item.kind === "notification");
  const messages = items.filter((item) => item.kind !== "notification");
  if (items.length === 0) return null;

  return (
    <>
      {messages.length > 0 ? (
        <div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex flex-col items-center gap-2 px-4">
          {messages.map((item) => (
            <div
              key={item.id}
              role="status"
              className={`pointer-events-auto w-full max-w-md rounded-xl border px-4 py-3 text-center text-sm font-medium shadow-[0px_10px_15px_-3px_rgba(0,0,0,0.1)] ${
                item.ok
                  ? "border-[#C9A84C] bg-white text-[#1A1A2E]"
                  : "border-red-200 bg-red-50 text-red-600"
              }`}
            >
              {item.message}
            </div>
          ))}
        </div>
      ) : null}
      {notices.length > 0 ? (
        <div className="pointer-events-none fixed start-4 top-4 z-[60] flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2">
          {notices.map((item) => (
            <Link
              key={item.id}
              href={item.href || "/notifications"}
              className="pointer-events-auto flex items-start gap-3 rounded-2xl border border-[#E8E4D9] bg-white p-4 shadow-[0px_18px_40px_-18px_rgba(26,26,46,0.45)]"
            >
              <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-[#C9A84C] via-[#E8C94A] to-[#A07830] text-[#1A1A2E]">
                <Bell className="size-5" />
              </span>
              <span className="min-w-0 flex-1 text-start">
                <span className="block text-sm font-bold leading-5 text-[#1A1A2E]">
                  {item.title || item.message}
                </span>
                {item.body ? (
                  <span className="mt-1 block text-xs leading-5 text-[#4A4A6A]">{item.body}</span>
                ) : null}
              </span>
            </Link>
          ))}
        </div>
      ) : null}
    </>
  );
}
