"use client";

import { useState } from "react";
import { createPortal } from "react-dom";
import { X, Tag, Loader2, Check } from "lucide-react";
import { useCurrency } from "@/lib/currency";
import { sfx } from "@/lib/sfx";
import type { MarketplaceListing } from "@/lib/types";
import clsx from "clsx";

/** Send the seller a price offer without leaving the page you're on. */
export function MakeOfferModal({
  listing,
  onClose,
}: {
  listing: MarketplaceListing;
  onClose: () => void;
}) {
  const { format: money, symbol } = useCurrency();
  const [amount, setAmount] = useState("");
  const [note, setNote] = useState("");
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  async function send() {
    setSending(true);
    // /api/messages has no POST handler — create the thread, then post into it.
    const started = await fetch("/api/messages/start", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        username: listing.seller.username,
        listingId: listing.id,
      }),
    }).catch(() => null);

    if (started && started.ok) {
      const { id } = await started.json();
      await fetch(`/api/messages/${id}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          text: `💰 Offer: ${money(Number(amount))} for "${listing.title}"${
            note ? ` — ${note}` : ""
          }`,
        }),
      }).catch(() => {});
    }

    setSending(false);
    sfx.fanfare();
    setSent(true);
    setTimeout(onClose, 1700);
  }

  return createPortal(
    <div className="nm-back" onClick={sending ? undefined : onClose}>
      <div className="cl-card" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
        {sent ? (
          <div className="fb-done">
            <span className="fb-done-icon">
              <Check size={34} />
            </span>
            <b>Offer sent</b>
            <span>
              {listing.seller.name.split(" ")[0]} will see it in Messages and can accept,
              decline or counter.
            </span>
          </div>
        ) : (
          <>
            <div className="cl-head">
              <span className="cl-title">Make an offer</span>
              <button onClick={onClose} className="nm-x">
                <X size={18} />
              </button>
            </div>

            <div className="cl-body">
              <p className="text-[13px] text-neutral-500">
                <b>{listing.title}</b> is listed at <b>{money(listing.price)}</b>.
              </p>

              <div className="of-quick">
                {[0.9, 0.8, 0.7].map((pct) => {
                  const v = String(Math.round(listing.price * pct));
                  return (
                    <button
                      key={pct}
                      onClick={() => setAmount(v)}
                      className={clsx("of-chip", amount === v && "on")}
                    >
                      {money(Number(v))}
                      <em>-{Math.round((1 - pct) * 100)}%</em>
                    </button>
                  );
                })}
              </div>

              <div>
                <label className="cl-label">Your offer</label>
                <div className="cl-price">
                  <span>{symbol}</span>
                  <input
                    type="number"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                    placeholder={String(listing.price)}
                  />
                </div>
              </div>

              <div>
                <label className="cl-label">Message (optional)</label>
                <textarea
                  value={note}
                  onChange={(e) => setNote(e.target.value.slice(0, 300))}
                  rows={3}
                  placeholder="Can collect this weekend..."
                  className="cl-field resize-none"
                />
              </div>
            </div>

            <div className="cl-foot">
              <button
                disabled={!amount || sending}
                onClick={send}
                className={clsx("cl-post", (!amount || sending) && "opacity-50")}
              >
                {sending ? (
                  <span className="inline-flex items-center gap-2">
                    <Loader2 size={15} className="animate-spin" /> Sending…
                  </span>
                ) : (
                  <span className="inline-flex items-center gap-2">
                    <Tag size={15} /> Send offer
                  </span>
                )}
              </button>
            </div>
          </>
        )}
      </div>
    </div>,
    document.body
  );
}
