import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { CheckCircle2, LoaderCircle, XCircle } from "lucide-react";
import { Button } from "@edr/ui-common";
import { api } from "@/services/api";

function extractOrderId(): string | null {
  const params = new URLSearchParams(window.location.search);
  const fromQuery = params.get("merch_order_id");
  if (fromQuery) return fromQuery;
  const segments = window.location.pathname.split("/").filter(Boolean);
  return segments[segments.length - 1] ?? null;
}

export default function CheckPaymentPage() {
  const navigate = useNavigate();
  const orderId = useMemo(() => extractOrderId(), []);

  const { data, isLoading, isError, error } = useQuery(
    api.bookings.checkPayment.queryOptions({
      input: { orderId: orderId! },
      enabled: !!orderId,
      retry: false,
    }),
  );

  const isSuccess = data?.status === "PAY_SUCCESS";

  if (!orderId) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background p-4">
        <div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 text-center shadow-sm">
          <div className="flex flex-col items-center gap-4">
            <XCircle className="size-10 text-destructive" />
            <p className="text-lg font-bold text-foreground">
              No payment reference found
            </p>
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate("/bookings")}
            >
              Back to My Bookings
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 text-center shadow-sm">
        {isLoading && (
          <div className="flex flex-col items-center gap-4">
            <LoaderCircle className="size-10 animate-spin text-primary" />
            <p className="text-lg font-semibold text-foreground">
              Checking payment status…
            </p>
          </div>
        )}

        {isSuccess && (
          <div className="flex flex-col items-center gap-4">
            <div className="flex size-14 items-center justify-center rounded-full bg-primary/10">
              <CheckCircle2 className="size-8 text-primary" />
            </div>
            <p className="text-lg font-bold text-foreground">
              Payment was successful!
            </p>
            <p className="text-sm text-muted-foreground">
              Your booking has been confirmed and payment is complete.
            </p>
            <Button
              type="button"
              onClick={() => navigate("/bookings")}
              className="mt-2"
            >
              Go to My Bookings
            </Button>
          </div>
        )}

        {!isLoading && data && !isSuccess && (
          <div className="flex flex-col items-center gap-4">
            <div className="flex size-14 items-center justify-center rounded-full bg-destructive/10">
              <XCircle className="size-8 text-destructive" />
            </div>
            <p className="text-lg font-bold text-foreground">
              Payment status: {data.status}
            </p>
            <p className="text-sm text-muted-foreground">
              Please try again or contact support if the issue persists.
            </p>
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate("/bookings")}
              className="mt-2"
            >
              Back to My Bookings
            </Button>
          </div>
        )}

        {isError && (
          <div className="flex flex-col items-center gap-4">
            <div className="flex size-14 items-center justify-center rounded-full bg-destructive/10">
              <XCircle className="size-8 text-destructive" />
            </div>
            <p className="text-lg font-bold text-foreground">
              Something went wrong
            </p>
            <p className="text-sm text-muted-foreground">
              {error instanceof Error
                ? error.message
                : "Failed to check payment status."}
            </p>
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate("/bookings")}
              className="mt-2"
            >
              Back to My Bookings
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
