"use client";
import { useMemo } from "react";
import { useAtom } from "jotai";
import { Section } from "../section";
import { formAtom, computedFeeAtom } from "@/components/state/autionAtoms";
import { useTranslations } from "next-intl";
import PaymentMethodSelector from "@/components/payment/PaymentMethodSelector";
import { usePaymentSuccess } from "@/hooks/usePaymentSuccess";
import { usePaymentFailure } from "@/hooks/usePaymentFailure";
import { usePaymentCancelled } from "@/hooks/usePaymentCancelled";

export function Step8({ onSuccess }: { onSuccess?: () => void }) {
  const t = useTranslations("ADD_LISTING.STEP8");

  // Handle returning from external payment success/failure
  usePaymentSuccess();
  usePaymentFailure();
  usePaymentCancelled();
  const [form] = useAtom(formAtom);
  const [fee] = useAtom(computedFeeAtom);

  const payment_purpose =
    form.offer === "fixed" ? "publish_offer" : "publish_auction";

  const REQUIRED = fee;

  const rawCreatedId: any = form.createdId;
  const createdIdValue =
    rawCreatedId && typeof rawCreatedId === "object"
      ? (rawCreatedId.id ?? String(rawCreatedId))
      : rawCreatedId;

  const paymentParams = useMemo(() => {
    const params: any = { payment_purpose };
    if (form.offer === "fixed") {
      params.offer_id = createdIdValue;
    } else {
      params.auction_id = createdIdValue;
    }
    return params;
  }, [payment_purpose, form.offer, createdIdValue]);

  return (
    <Section title={t("title")}>
      <div className="w-full mx-auto">
        <section className="bg-white rounded-2xl shadow-xl overflow-hidden mb-4">
          <div className="bg-[#0f5132] text-white px-5 py-4 flex items-center justify-between">
            <div className="flex items-center gap-2 flex-wrap">
              <strong className="text-base">
                {form.offer === "fixed"
                  ? t("header_listing_fee")
                  : t("header_auction_fee")}
              </strong>
            </div>
            <small className="opacity-90">{t("header_note")}</small>
          </div>
          <div className="px-5 py-4">
            <PaymentMethodSelector
              amount={REQUIRED}
              paymentParams={paymentParams}
              disabled={!createdIdValue}
              onSuccess={onSuccess}
              showSummary={true}
            />

            <ul className="mt-4 text-[13px] text-slate-700 bg-white rounded-xl border border-[#eef2f0] p-3">
              <li>{t("terms_line1")}</li>
              <li>{t("terms_line2")}</li>
            </ul>
          </div>
        </section>
      </div>
    </Section>
  );
}

export default Step8;
