"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import { MobileShell } from "@/app/_components/core";
import {
  buildPendingPaymentSubscriptionUrl,
  getPendingPaymentOrder,
} from "@/lib/payment/pending_payment_order";
import { ROUTES } from "@/router/routes";

type ReturnStatus = "loading" | "missing";

export default function SubscriptionReturnPage() {
  const router = useRouter();
  const [status, setStatus] = useState<ReturnStatus>("loading");

  useEffect(() => {
    let cancelled = false;

    const redirectToSubscription = async () => {
      const result = await getPendingPaymentOrder();
      if (cancelled) return;

      if (result.success && result.data !== null) {
        router.replace(buildPendingPaymentSubscriptionUrl(result.data));
        return;
      }

      setStatus("missing");
    };

    void redirectToSubscription();
    return () => {
      cancelled = true;
    };
  }, [router]);

  return (
    <MobileShell>
      <div
        style={{
          minHeight: "60vh",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          gap: "0.75rem",
          padding: "2rem 1.5rem",
          textAlign: "center",
        }}
      >
        <h1 style={{ margin: 0, fontSize: "1.5rem", fontWeight: 600 }}>
          Returning to subscription
        </h1>
        <p style={{ margin: 0, color: "#666", lineHeight: 1.5 }}>
          {status === "loading"
            ? "We are restoring your payment order."
            : "No pending payment order was found. Please return to the subscription page."}
        </p>
        {status === "missing" ? (
          <button
            type="button"
            onClick={() => router.replace(ROUTES.subscription)}
            style={{
              marginTop: "0.5rem",
              padding: "0.75rem 1.5rem",
              border: "none",
              borderRadius: "12px",
              background: "linear-gradient(135deg, #f96ADE, #f657A0)",
              color: "white",
              cursor: "pointer",
              fontSize: "1rem",
              fontWeight: 600,
            }}
          >
            Back to subscription
          </button>
        ) : null}
      </div>
    </MobileShell>
  );
}
