"use client";

import { useState, useSyncExternalStore } from "react";

import type { CheckoutIntent } from "@/data/schemas/auth";
import {
  DEFAULT_CHARACTER_SLUG,
  getCharacterBySlug,
} from "@/data/constants/character";
import { createCheckoutHandoff } from "@/lib/auth/checkout_handoff";
import { BrowserDetector } from "@/utils/browser-detect";
import { ExceptionHandler } from "@/core/errors";
import { Result } from "@/utils/result";
import { UrlLauncherUtil } from "@/utils/url-launcher-util";

export interface ExternalBrowserCheckoutButtonProps {
  checkoutIntent: CheckoutIntent;
  disabled?: boolean;
  characterSlug?: string;
}

export function ExternalBrowserCheckoutButton({
  checkoutIntent,
  disabled = false,
  characterSlug = DEFAULT_CHARACTER_SLUG,
}: ExternalBrowserCheckoutButtonProps) {
  const isFacebookBrowser = useSyncExternalStore(
    () => () => undefined,
    () => BrowserDetector.isFacebookInAppBrowser(),
    () => false,
  );
  const [isOpening, setIsOpening] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  if (!isFacebookBrowser) return null;

  const handleOpen = async () => {
    if (disabled || isOpening) return;
    setIsOpening(true);
    setErrorMessage(null);
    const result = await createCheckoutHandoff(checkoutIntent);
    if (Result.isErr(result)) {
      setErrorMessage(
        ExceptionHandler.message(
          result.error,
          "Could not open this checkout in your browser. Please sign in and try again.",
        ),
      );
      setIsOpening(false);
      return;
    }
    try {
      const verifiedCharacter =
        getCharacterBySlug(characterSlug)?.slug ?? DEFAULT_CHARACTER_SLUG;
      const externalUrl = new URL(
        result.data.externalUrl,
        window.location.origin,
      );
      externalUrl.searchParams.set("character", verifiedCharacter);
      UrlLauncherUtil.openUrlWithExternalBrowser(externalUrl.toString());
    } catch (error) {
      setErrorMessage(
        ExceptionHandler.message(
          error,
          "Could not open this checkout in your browser. Please try again.",
        ),
      );
      setIsOpening(false);
    }
  };

  return (
    <div className="mb-2 w-full text-center">
      <button
        type="button"
        className="min-h-11 w-full cursor-pointer rounded-full border border-black/15 bg-white px-4 py-2.5 text-sm font-semibold text-text-foreground disabled:cursor-not-allowed disabled:opacity-55"
        disabled={disabled || isOpening}
        onClick={() => void handleOpen()}
      >
        {isOpening
          ? "Opening browser..."
          : "Open in browser for more payment methods"}
      </button>
      {errorMessage ? (
        <p className="mt-2 text-sm text-[#c0392b]" role="alert">
          {errorMessage}
        </p>
      ) : null}
    </div>
  );
}
