"use client";

import { useCallback, useEffect, useState } from "react";
import type { ProductPublic } from "@/lib/products";
import { centsToBrl } from "@/lib/landing-default";

type ProductOffer = {
  id: string;
  offerProductId: string;
  offerType: "orderbump" | "upsell";
  title: string;
  description: string;
  priceCents: number;
  anchorPriceCents: number | null;
  highlightTag: string;
  offerProduct?: { slug: string; name: string; emoji: string };
};

type Props = {
  productSlug: string;
  allProducts: ProductPublic[];
};

type Draft = {
  offerProductId: string;
  title: string;
  description: string;
  price: string;
  anchorPrice: string;
  highlightTag: string;
};

const emptyDraft = (): Draft => ({
  offerProductId: "",
  title: "",
  description: "",
  price: "",
  anchorPrice: "",
  highlightTag: "",
});

export default function ProductOffersEditor({ productSlug, allProducts }: Props) {
  const [orderBumps, setOrderBumps] = useState<ProductOffer[]>([]);
  const [upsells, setUpsells] = useState<ProductOffer[]>([]);
  const [bumpDraft, setBumpDraft] = useState<Draft>(emptyDraft());
  const [upsellDraft, setUpsellDraft] = useState<Draft>(emptyDraft());
  const [editingBumpId, setEditingBumpId] = useState<string | null>(null);
  const [editingUpsellId, setEditingUpsellId] = useState<string | null>(null);
  const [msg, setMsg] = useState("");

  const others = allProducts.filter((p) => p.slug !== productSlug && p.status === "ativo");

  const load = useCallback(async () => {
    const res = await fetch(`/api/products/${productSlug}/offers`, { credentials: "include" });
    const data = await res.json();
    setOrderBumps(data.orderBumps || []);
    setUpsells(data.upsells || []);
  }, [productSlug]);

  useEffect(() => {
    load();
  }, [load]);

  async function saveOffer(type: "orderbump" | "upsell", draft: Draft) {
    if (!draft.offerProductId || !draft.price) {
      setMsg("Escolha o produto e o preço da oferta");
      return;
    }
    setMsg("");
    const editingId = type === "orderbump" ? editingBumpId : editingUpsellId;
    const res = await fetch(`/api/products/${productSlug}/offers`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({
        id: editingId || undefined,
        offerType: type,
        offerProductId: draft.offerProductId,
        title: draft.title,
        description: draft.description,
        price: draft.price,
        anchorPrice: draft.anchorPrice || undefined,
        highlightTag: draft.highlightTag,
      }),
    });
    const data = await res.json();
    if (!res.ok) {
      setMsg(data.error || "Erro ao salvar");
      return;
    }
    if (type === "orderbump") {
      setBumpDraft(emptyDraft());
      setEditingBumpId(null);
    } else {
      setUpsellDraft(emptyDraft());
      setEditingUpsellId(null);
    }
    await load();
    setMsg(editingId ? "Oferta atualizada!" : "Oferta salva!");
    setTimeout(() => setMsg(""), 2000);
  }

  async function removeOffer(id: string, type: "orderbump" | "upsell") {
    if (!confirm("Remover esta oferta?")) return;
    const res = await fetch(`/api/products/${productSlug}/offers`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ id, delete: true }),
    });
    const data = await res.json();
    if (!res.ok) {
      setMsg(data.error || "Erro ao remover");
      return;
    }
    if (type === "orderbump" && editingBumpId === id) {
      setEditingBumpId(null);
      setBumpDraft(emptyDraft());
    }
    if (type === "upsell" && editingUpsellId === id) {
      setEditingUpsellId(null);
      setUpsellDraft(emptyDraft());
    }
    await load();
    setMsg("Oferta removida");
    setTimeout(() => setMsg(""), 2000);
  }

  function startEdit(offer: ProductOffer, type: "orderbump" | "upsell") {
    const draft: Draft = {
      offerProductId: offer.offerProductId,
      title: offer.title,
      description: offer.description,
      price: centsToBrl(offer.priceCents),
      anchorPrice: offer.anchorPriceCents ? centsToBrl(offer.anchorPriceCents) : "",
      highlightTag: offer.highlightTag,
    };
    if (type === "orderbump") {
      setEditingBumpId(offer.id);
      setBumpDraft(draft);
    } else {
      setEditingUpsellId(offer.id);
      setUpsellDraft(draft);
    }
    setMsg("");
  }

  function cancelEdit(type: "orderbump" | "upsell") {
    if (type === "orderbump") {
      setEditingBumpId(null);
      setBumpDraft(emptyDraft());
    } else {
      setEditingUpsellId(null);
      setUpsellDraft(emptyDraft());
    }
  }

  function renderList(offers: ProductOffer[], type: "orderbump" | "upsell") {
    if (!offers.length) {
      return (
        <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.45)", marginBottom: 10 }}>
          Nenhuma oferta configurada.
        </p>
      );
    }
    return offers.map((o) => (
      <div key={o.id} className="offer-row">
        <div>
          <b>
            {o.offerProduct?.emoji} {o.title || o.offerProduct?.name}
          </b>
          <span style={{ display: "block", fontSize: ".75rem", color: "rgba(255,255,255,.5)" }}>
            R$ {(o.priceCents / 100).toFixed(2).replace(".", ",")}
            {o.anchorPriceCents ? (
              <s style={{ marginLeft: 8 }}>
                R$ {(o.anchorPriceCents / 100).toFixed(2).replace(".", ",")}
              </s>
            ) : null}
          </span>
        </div>
        <div className="offer-row-actions">
          <button
            type="button"
            className="content-edit"
            title="Editar"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              startEdit(o, type);
            }}
          >
            ✏️
          </button>
          <button
            type="button"
            className="content-del"
            title="Remover"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              removeOffer(o.id, type);
            }}
          >
            ×
          </button>
        </div>
      </div>
    ));
  }

  function renderForm(
    type: "orderbump" | "upsell",
    draft: Draft,
    setDraft: (d: Draft) => void,
    editingId: string | null
  ) {
    return (
      <div className="offer-form">
        {editingId ? (
          <p style={{ fontSize: ".78rem", color: "#c8f135", marginBottom: 8 }}>
            Editando oferta — altere os campos e salve
          </p>
        ) : null}
        <select
          value={draft.offerProductId}
          onChange={(e) => setDraft({ ...draft, offerProductId: e.target.value })}
          style={{
            width: "100%",
            marginBottom: 8,
            padding: 8,
            borderRadius: 8,
            background: "#1a1a1a",
            color: "#fff",
            border: "1px solid rgba(255,255,255,.15)",
          }}
        >
          <option value="">Escolher produto…</option>
          {others.map((p) => (
            <option key={p.id} value={p.id}>
              {p.emoji} {p.name} (R$ {p.price})
            </option>
          ))}
        </select>
        <input
          placeholder="Título da oferta (opcional)"
          value={draft.title}
          onChange={(e) => setDraft({ ...draft, title: e.target.value })}
          style={{ width: "100%", marginBottom: 6, padding: 8, borderRadius: 8 }}
        />
        <textarea
          placeholder="Descrição curta"
          value={draft.description}
          onChange={(e) => setDraft({ ...draft, description: e.target.value })}
          rows={2}
          style={{ width: "100%", marginBottom: 6, padding: 8, borderRadius: 8, resize: "vertical" }}
        />
        <div style={{ display: "flex", gap: 8, marginBottom: 6 }}>
          <input
            placeholder="Preço R$"
            value={draft.price}
            onChange={(e) => setDraft({ ...draft, price: e.target.value })}
            style={{ flex: 1, padding: 8, borderRadius: 8 }}
          />
          <input
            placeholder="De R$ (âncora)"
            value={draft.anchorPrice}
            onChange={(e) => setDraft({ ...draft, anchorPrice: e.target.value })}
            style={{ flex: 1, padding: 8, borderRadius: 8 }}
          />
        </div>
        <input
          placeholder="Tag destaque (ex: 50% OFF)"
          value={draft.highlightTag}
          onChange={(e) => setDraft({ ...draft, highlightTag: e.target.value })}
          style={{ width: "100%", marginBottom: 8, padding: 8, borderRadius: 8 }}
        />
        <div style={{ display: "flex", gap: 8 }}>
          <button
            type="button"
            className="content-add-btn"
            style={{ flex: 1 }}
            onClick={() => saveOffer(type, draft)}
            disabled={!others.length}
          >
            {editingId ? "Salvar alterações" : `+ Adicionar ${type === "orderbump" ? "order bump" : "upsell"}`}
          </button>
          {editingId ? (
            <button
              type="button"
              className="content-add-btn"
              style={{ flex: "0 0 auto", background: "rgba(255,255,255,.06)", color: "#fff", borderStyle: "solid" }}
              onClick={() => cancelEdit(type)}
            >
              Cancelar
            </button>
          ) : null}
        </div>
        {!others.length ? (
          <p style={{ fontSize: ".72rem", color: "rgba(255,255,255,.4)", marginTop: 6 }}>
            Crie outro produto ativo para usar como oferta.
          </p>
        ) : null}
      </div>
    );
  }

  return (
    <div>
      <div className="grp">
        <label>5. Order bump (checkout)</label>
        <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.5)", marginBottom: 10 }}>
          Ofertas extras com checkbox na página de pagamento — estilo Kirvano.
        </p>
        {renderList(orderBumps, "orderbump")}
        {renderForm("orderbump", bumpDraft, setBumpDraft, editingBumpId)}
      </div>

      <div className="grp">
        <label>6. Upsell (após compra)</label>
        <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.5)", marginBottom: 10 }}>
          Produtos com desconto na página de obrigado, logo após o pagamento.
        </p>
        {renderList(upsells, "upsell")}
        {renderForm("upsell", upsellDraft, setUpsellDraft, editingUpsellId)}
      </div>

      {msg ? <p style={{ fontSize: ".78rem", color: "#c8f135", marginTop: 8 }}>{msg}</p> : null}
    </div>
  );
}
