"use client";

import { Suspense, useCallback, useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useAction } from "convex/react";
import Link from "next/link";
import { Card, Spinner } from "@heroui/react";
import { api } from "../../../../../../convex/_generated/api";

type PageState =
  | { phase: "loading" }
  | { phase: "complete"; email: string | null }
  | { phase: "incomplete" }
  | { phase: "error"; message: string };

// ─── Main Content (inside Suspense) ──────────────────────────────────────────

function SuccessContent() {
  const searchParams = useSearchParams();
  const sessionId = searchParams.get("session_id");
  const getStatus = useAction(api.stripeActions.getCheckoutSessionStatus);
  const [state, setState] = useState<PageState>({ phase: "loading" });
  const fetchRef = useRef(0);

  const fetchStatus = useCallback(async () => {
    if (!sessionId) {
      setState({
        phase: "error",
        message:
          "No payment session found. If you completed a payment, please check your email for confirmation.",
      });
      return;
    }

    const id = ++fetchRef.current;
    setState({ phase: "loading" });

    try {
      const result = await getStatus({ sessionId });
      if (id !== fetchRef.current) return;

      if (result.status === "complete") {
        setState({ phase: "complete", email: result.customerEmail });
      } else {
        setState({ phase: "incomplete" });
      }
    } catch {
      if (id !== fetchRef.current) return;
      setState({
        phase: "error",
        message:
          "Unable to retrieve payment status. Please check your email for confirmation or contact support.",
      });
    }
  }, [sessionId, getStatus]);

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

  if (state.phase === "loading") {
    return <LoadingState />;
  }

  return (
    <div className="flex min-h-[60vh] items-center justify-center">
      <Card className="w-full max-w-md rounded-xl p-6 md:p-8">
        <Card.Content className="flex flex-col items-center gap-5 p-0 text-center">
          {state.phase === "complete" && (
            <CompleteView email={state.email} />
          )}
          {state.phase === "incomplete" && <IncompleteView />}
          {state.phase === "error" && <ErrorView message={state.message} />}
        </Card.Content>
      </Card>
    </div>
  );
}

// ─── State Views ─────────────────────────────────────────────────────────────

function CompleteView({ email }: { email: string | null }) {
  return (
    <>
      <div className="flex size-16 items-center justify-center rounded-full bg-emerald-50">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth={1.5}
          stroke="currentColor"
          className="size-8 text-[#236f6b]"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
          />
        </svg>
      </div>

      <div className="space-y-2">
        <h1 className="font-[family-name:var(--font-fraunces)] text-2xl font-semibold">
          Payment successful!
        </h1>
        {email && (
          <p className="text-sm text-default-500">
            A confirmation has been sent to{" "}
            <span className="font-medium text-foreground">{email}</span>.
          </p>
        )}
        <p className="text-sm text-default-500">
          Your order has been placed and you&apos;ll receive a confirmation
          email shortly.
        </p>
      </div>

      <div className="flex w-full flex-col gap-2 pt-2">
        <Link
          href="/account/orders"
          className="inline-flex items-center justify-center rounded-lg gap-2 px-4 py-3 w-full bg-[#236f6b] font-medium text-white hover:bg-[#1e5f5b] transition-colors text-base"
        >
          View your orders
        </Link>
        <Link
          href="/shop"
          className="inline-flex items-center justify-center rounded-medium gap-2 px-4 py-3 w-full bg-transparent hover:bg-default-100 text-foreground font-medium transition-colors"
        >
          Continue shopping
        </Link>
      </div>
    </>
  );
}

function IncompleteView() {
  return (
    <>
      <div className="flex size-16 items-center justify-center rounded-full bg-amber-50">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth={1.5}
          stroke="currentColor"
          className="size-8 text-amber-600"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"
          />
        </svg>
      </div>

      <div className="space-y-2">
        <h1 className="font-[family-name:var(--font-fraunces)] text-2xl font-semibold">
          Payment was not completed
        </h1>
        <p className="text-sm text-default-500">
          Your payment was not completed. No charges have been made. You can
          return to checkout to try again.
        </p>
      </div>

      <div className="flex w-full flex-col gap-2 pt-2">
        <Link
          href="/checkout"
          className="inline-flex items-center justify-center rounded-lg gap-2 px-4 py-3 w-full bg-[#236f6b] font-medium text-white hover:bg-[#1e5f5b] transition-colors text-base"
        >
          Return to checkout
        </Link>
        <Link
          href="/shop"
          className="inline-flex items-center justify-center rounded-medium gap-2 px-4 py-3 w-full bg-transparent hover:bg-default-100 text-foreground font-medium transition-colors"
        >
          Continue shopping
        </Link>
      </div>
    </>
  );
}

function ErrorView({ message }: { message: string }) {
  return (
    <>
      <div className="flex size-16 items-center justify-center rounded-full bg-red-50">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth={1.5}
          stroke="currentColor"
          className="size-8 text-danger"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"
          />
        </svg>
      </div>

      <div className="space-y-2">
        <h1 className="font-[family-name:var(--font-fraunces)] text-2xl font-semibold">
          Something went wrong
        </h1>
        <p className="text-sm text-default-500">{message}</p>
      </div>

      <div className="flex w-full flex-col gap-2 pt-2">
        <Link
          href="/checkout"
          className="inline-flex items-center justify-center rounded-lg gap-2 px-4 py-3 w-full bg-[#236f6b] font-medium text-white hover:bg-[#1e5f5b] transition-colors text-base"
        >
          Return to checkout
        </Link>
        <Link
          href="/"
          className="inline-flex items-center justify-center rounded-medium gap-2 px-4 py-3 w-full bg-transparent hover:bg-default-100 text-foreground font-medium transition-colors"
        >
          Go to homepage
        </Link>
      </div>
    </>
  );
}

// ─── Loading State ───────────────────────────────────────────────────────────

function LoadingState() {
  return (
    <div
      className="flex min-h-[60vh] flex-col items-center justify-center gap-4"
      role="status"
    >
      <Spinner size="lg" />
      <p className="text-sm text-default-500">Verifying your payment…</p>
    </div>
  );
}

// ─── Page Export ──────────────────────────────────────────────────────────────

export default function CheckoutSuccessPage() {
  return (
    <Suspense fallback={<LoadingState />}>
      <SuccessContent />
    </Suspense>
  );
}
