"use client";

import { fetchOnce } from "@/lib/fetch-once";

import { useModule } from "@/lib/modules";

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X, Loader2, Check } from "lucide-react";
import { sfx } from "@/lib/sfx";
import { firework } from "@/lib/particles";
import type { Gift } from "@/lib/types";
import clsx from "clsx";

/** Pick a gift and send it. */
export function GiftModal({
  username,
  name,
  onClose,
}: {
  username: string;
  name: string;
  onClose: () => void;
}) {
  // Hidden when this module is switched off in System settings.
  const moduleOn = useModule("gifts");

  const [gifts, setGifts] = useState<Gift[]>([]);
  const [picked, setPicked] = useState<string | null>(null);
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchOnce<Record<string, unknown>>("/api/settings")
      .then((d) => d)
      .then(() => fetch("/api/gifts"))
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setGifts(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  async function send(e: React.MouseEvent) {

  if (!moduleOn) return null;

    if (!picked) return;
    setSending(true);
    setError(null);

    const res = await fetch("/api/wallet/gift", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ giftId: picked, username }),
    }).catch(() => null);

    setSending(false);
    const d = res ? await res.json() : null;

    if (!res || !res.ok) {
      setError(d?.error ?? "Couldn't send that gift");
      return;
    }

    setSent(true);
    sfx.fanfare();
    firework(e.currentTarget as HTMLElement, ["#f59e0b", "#ec4899", "#7c3aed"]);
    setTimeout(onClose, 1600);
  }

  const chosen = gifts.find((g) => g.id === picked);

  return createPortal(
    <div className="nm-back" onClick={onClose}>
      <div className="gm-card" onClick={(e) => e.stopPropagation()}>
        <div className="cl-head">
          <span className="cl-title">Send {name} a gift</span>
          <button onClick={onClose} className="nm-x">
            <X size={18} />
          </button>
        </div>

        {sent ? (
          <div className="gm-done">
            <span>{chosen?.emoji}</span>
            <b>Gift sent</b>
            <em>{name} has been told.</em>
          </div>
        ) : (
          <>
            <div className="gm-grid">
              {gifts.map((g) => (
                <button
                  key={g.id}
                  onClick={() => setPicked(g.id)}
                  className={clsx("gm-gift", picked === g.id && "on")}
                >
                  <span className="gm-emoji">{g.emoji}</span>
                  <b>{g.name}</b>
                  <em>${g.price}</em>
                </button>
              ))}
            </div>

            {gifts.length === 0 && (
              <p className="ps-hint">No gifts are available right now.</p>
            )}

            {error && <p className="cl-error">{error}</p>}

            <button
              onClick={send}
              disabled={!picked || sending}
              className={clsx("gm-send", !picked && "off")}
            >
              {sending ? (
                <Loader2 size={15} className="animate-spin" />
              ) : (
                <Check size={15} />
              )}
              {chosen ? `Send ${chosen.name} — $${chosen.price}` : "Choose a gift"}
            </button>
          </>
        )}
      </div>
    </div>,
    document.body
  );
}
