"use client";

import { usePaymentLaunchFlow } from "@/app/_hooks/use-payment-launch-flow";
import { PaymentLaunchDialogs } from "@/app/_components/payment/payment-launch-dialogs";
import { ExternalBrowserCheckoutButton } from "@/app/_components/payment/external-browser-checkout-button";
import { useActiveCharacter } from "@/providers/character-provider";
import {
  usePaymentDispatch,
  usePaymentState,
} from "@/stores/payment/payment-context";
import { Logger } from "@/utils/logger";

import styles from "./tip-screen.module.css";

const log = new Logger("TipCheckoutButton");

export interface TipCheckoutButtonProps {
  giftCategory: string | null;
  giftPlanId: string | null;
  disabled?: boolean;
  onOrder: () => void;
  returnPath: string;
}

export function TipCheckoutButton({
  giftCategory,
  giftPlanId,
  disabled = false,
  onOrder,
  returnPath,
}: TipCheckoutButtonProps) {
  const character = useActiveCharacter();
  const payment = usePaymentState();
  const paymentDispatch = usePaymentDispatch();
  const paymentLaunch = usePaymentLaunchFlow({
    log,
    logScope: "tip-checkout",
    payment,
    paymentDispatch,
    subscriptionType: "tip",
    giftCategory,
    giftPlanId,
    characterSlug: character.slug,
  });

  const isResumingQris = paymentLaunch.hasHiddenQrisPayment;
  const isLoading =
    payment.isCreatingOrder || (payment.isPollingOrder && !isResumingQris);
  const label = isResumingQris
    ? "Resume QRIS payment"
    : payment.isPollingOrder
      ? "Processing payment..."
      : payment.isCreatingOrder
        ? "Creating order..."
        : payment.isPaid
          ? "Thanks for the coffee"
          : "Order and Buy";

  return (
    <>
      <button
        type="button"
        data-analytics-key="tip.checkout"
        data-analytics-label="Buy coffee tip"
        className={styles.checkoutButton}
        disabled={(disabled && !isResumingQris) || isLoading}
        onClick={isResumingQris ? paymentLaunch.handleQrisResume : onOrder}
      >
        {label}
      </button>
      {payment.payChannel === "stripe" && payment.selectedPlanId ? (
        <ExternalBrowserCheckoutButton
          disabled={disabled || isLoading}
          checkoutIntent={{
            planId: payment.selectedPlanId,
            autoRenew: false,
            recipientCharacterId: character.id,
            ...(payment.chatActionId
              ? { chatActionId: payment.chatActionId }
              : {}),
          }}
        />
      ) : null}
      {payment.errorMessage ? (
        <p className={styles.checkoutError} role="alert">
          {payment.errorMessage}
        </p>
      ) : null}
      <PaymentLaunchDialogs
        currentOrderId={payment.currentOrderId}
        externalCheckoutAnalyticsKey="tip.external_checkout"
        ezpayDescription="Your gift order is ready. Continue to the secure payment page to finish."
        launch={paymentLaunch}
        stripeReturnPath={returnPath}
      />
    </>
  );
}
