"use client";

import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import { ShieldCheckIcon } from "@/components/dashboard-icons";

type ToastKind = "success" | "warning" | "error";

type ToastData = {
  id: string;
  kind: ToastKind;
  text: string;
  actions?: { label: string; href: string }[];
};

const kindStyles: Record<ToastKind, string> = {
  success: "border-emerald-200 bg-emerald-50 text-emerald-800",
  warning: "border-amber-200 bg-amber-50 text-amber-800",
  error: "border-rose-200 bg-rose-50 text-rose-800",
};

let toastIdCounter = 0;
let addToastFn: ((toast: ToastData) => void) | null = null;

export function toast(kind: ToastKind, text: string, actions?: { label: string; href: string }[]) {
  if (addToastFn) {
    addToastFn({ id: String(++toastIdCounter), kind, text, actions });
  }
}

function ToastItem({ data, onClose }: { data: ToastData; onClose: (id: string) => void }) {
  useEffect(() => {
    const timer = setTimeout(() => onClose(data.id), 5000);
    return () => clearTimeout(timer);
  }, [data.id, onClose]);

  return (
    <div
      className={cn(
        "pointer-events-auto flex w-80 flex-col gap-2 rounded-2xl border px-4 py-3 text-sm shadow-lg",
        kindStyles[data.kind],
      )}
    >
      <div className="flex items-start gap-2">
        <ShieldCheckIcon className="mt-0.5 h-4 w-4 shrink-0" />
        <span className="flex-1">{data.text}</span>
        <button
          type="button"
          onClick={() => onClose(data.id)}
          className="ml-1 shrink-0 rounded-full p-0.5 hover:bg-black/5"
        >
          <svg className="h-3.5 w-3.5" viewBox="0 0 16 16" fill="currentColor">
            <path d="M4.646 4.646a.5.5 0 01.708 0L8 7.293l2.646-2.647a.5.5 0 01.708.708L8.707 8l2.647 2.646a.5.5 0 01-.708.708L8 8.707l-2.646 2.647a.5.5 0 01-.708-.708L7.293 8 4.646 5.354a.5.5 0 010-.708z" />
          </svg>
        </button>
      </div>
      {data.actions ? (
        <div className="flex flex-wrap gap-2">
          {data.actions.map((action) => (
            <a
              key={action.href}
              href={action.href}
              className="inline-flex h-8 items-center rounded-full border border-current px-3 text-xs font-medium hover:bg-black/5"
            >
              {action.label}
            </a>
          ))}
        </div>
      ) : null}
    </div>
  );
}

export function ToastContainer() {
  const [toasts, setToasts] = useState<ToastData[]>([]);

  useEffect(() => {
    addToastFn = (t) => setToasts((prev) => [...prev, t]);
    return () => {
      addToastFn = null;
    };
  }, []);

  function remove(id: string) {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }

  if (toasts.length === 0) return null;

  return (
    <div className="pointer-events-none fixed bottom-4 right-4 z-[100] flex flex-col gap-2">
      {toasts.map((t) => (
        <ToastItem key={t.id} data={t} onClose={remove} />
      ))}
    </div>
  );
}
