"use client";

import { useEffect, useState } from "react";
import type { ProductOfferPublic } from "@/lib/product-types";
import { moneyBrl } from "@/lib/landing-default";
import { applyCheckoutResult } from "@/lib/checkout-response";

type Props = {
  saleId: string;
  email: string;
};

export default function UpsellSection({ saleId, email }: Props) {
  const [upsells, setUpsells] = useState<ProductOfferPublic[]>([]);
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [pixCopy, setPixCopy] = useState<string | null>(null);
  const [pixImg, setPixImg] = useState<string | null>(null);
  const [doneIds, setDoneIds] = useState<string[]>([]);

  useEffect(() => {
    const q = new URLSearchParams({ saleId, email });
    fetch(`/api/checkout/upsells?${q}`)
      .then((r) => r.json())
      .then((d) => setUpsells(d.upsells || []))
      .catch(() => setUpsells([]));
  }, [saleId, email]);

  async function accept(offerId: string) {
    setLoadingId(offerId);
    setPixCopy(null);
    setPixImg(null);
    try {
      const res = await fetch("/api/checkout/upsell", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ parentSaleId: saleId, offerId }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Erro");

      const result = applyCheckoutResult(data, {
        onPix: (copy, qr) => {
          setPixCopy(copy);
          setPixImg(qr || null);
        },
      });

      if (result === "redirect" || data.demo) {
        setDoneIds((prev) => [...prev, offerId]);
      }
    } catch (e) {
      alert(e instanceof Error ? e.message : "Erro ao processar upsell");
    } finally {
      setLoadingId(null);
    }
  }

  const visible = upsells.filter((u) => !doneIds.includes(u.id));
  if (!visible.length && !pixCopy) return null;

  return (
    <div className="co-upsell">
      <h3>✨ Oferta exclusiva para você</h3>
      <p className="co-upsell-sub">Complemente sua compra com desconto — por tempo limitado nesta página.</p>

      {visible.map((u) => (
        <div key={u.id} className="co-upsell-card">
          <div className="co-upsell-head">
            <span>{u.emoji}</span>
            <div>
              <b>{u.title}</b>
              {u.highlightTag ? <span className="co-bump-tag">{u.highlightTag}</span> : null}
            </div>
          </div>
          {u.description ? <p>{u.description}</p> : null}
          <div className="co-bump-price" style={{ marginBottom: 12 }}>
            {u.anchorPrice ? <s>{moneyBrl(u.anchorPrice)}</s> : null}
            <strong>{moneyBrl(u.price)}</strong>
          </div>
          <button
            type="button"
            className="b lime sm"
            disabled={loadingId === u.id}
            onClick={() => accept(u.id)}
          >
            {loadingId === u.id ? "Processando…" : "Sim, quero adicionar!"}
          </button>
        </div>
      ))}

      {pixCopy ? (
        <div className="co-upsell-pix" style={{ marginTop: 20, textAlign: "left" }}>
          <p><b>Pague o Pix do upsell:</b></p>
          {pixImg ? <img src={pixImg} alt="QR Pix" style={{ maxWidth: 200, margin: "12px 0" }} /> : null}
          <textarea readOnly value={pixCopy} rows={3} style={{ width: "100%", fontSize: ".8rem" }} />
        </div>
      ) : null}
    </div>
  );
}
