"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import type { Order, Payment } from "@/types/order";
import { formatCurrency } from "@/lib/format";
import { PaymentStep } from "@/components/checkout/payment/payment-step";

const POLL_INTERVAL_MS = 4000;

/**
 * Custom Core API payment step (QRIS / bank VA — see PaymentStep) for the
 * order created in StepConfirmation, shown inline rather than redirecting
 * away. Tickets are issued ONLY after the payment success webhook callback
 * on the backend — this component never fake-issues them from client-side
 * state. It polls the order's own status while pending and, once the
 * webhook resolves it (paid or otherwise), hands off to the same
 * order-status page used by the general checkout flow.
 */
export function StepPayment({ order: initialOrder }: { order: Order }) {
  const router = useRouter();
  const [order, setOrder] = useState(initialOrder);

  useEffect(() => {
    if (order.status !== "pending") {
      router.push(`/checkout/status?order=${order.id}`);
      return;
    }

    let cancelled = false;

    const id = setInterval(async () => {
      try {
        const res = await fetch(`/api/checkout/${order.id}/status`, { cache: "no-store" });
        const body = await res.json().catch(() => null);
        if (!cancelled && res.ok) {
          setOrder(body.data as Order);
        }
      } catch {
        // Transient network hiccup — the next tick tries again.
      }
    }, POLL_INTERVAL_MS);

    return () => {
      cancelled = true;
      clearInterval(id);
    };
  }, [order.id, order.status, router]);

  const latestPayment = order.payments[order.payments.length - 1] ?? null;
  const activePayment = latestPayment && latestPayment.status === "pending" ? latestPayment : null;

  function handleCharged(payment: Payment) {
    setOrder((prev) => ({ ...prev, payments: [...prev.payments, payment] }));
  }

  return (
    <div className="mx-auto max-w-3xl px-6 py-8">
      <section className="rounded-2xl bg-neutral-100 p-6">
        <div className="flex items-center justify-between">
          <p className="font-signaturee text-lg font-semibold text-signaturee-red">Payment</p>
          <span className="text-sm text-neutral-500">No. {order.order_number}</span>
        </div>
        <div className="mt-1 flex items-center justify-between font-signaturee text-xl font-semibold">
          <span className="text-sm font-normal text-neutral-600">Total Due</span>
          <span className="text-signaturee-red">{formatCurrency(Number(order.total_amount))}</span>
        </div>
      </section>

      <section className="mt-4 overflow-hidden rounded-2xl bg-neutral-100 p-6">
        <p className="font-signaturee text-lg font-semibold text-signaturee-red">Choose Payment Method</p>
        <p className="mt-1 text-sm text-neutral-600">Complete your payment below.</p>

        <div className="mt-4">
          <PaymentStep orderId={order.id} latestPayment={activePayment} onCharged={handleCharged} />
        </div>
      </section>
    </div>
  );
}
