import { useState } from 'react';
import { notifications } from '@mantine/notifications';
import {
  extractErrorMessage,
  useInitiateDocumentPaymentMutation,
  useInitiatePaymentMutation,
  type InitiatePaymentResult,
} from '@ema-platform/api';

/**
 * Starts a payment and hands the browser over to the provider.
 *
 * Telebirr on web answers with a `REDIRECT` action carrying a signed checkout
 * URL; on mobile it answers with `LAUNCH_APP` so the Telebirr app can be opened
 * directly. Anything else means the provider gave us nothing to act on, which
 * is reported rather than silently doing nothing.
 */
export function useApplicationPayment() {
  const [initiate, { isLoading }] = useInitiatePaymentMutation();
  const [initiateDocument, { isLoading: isLoadingDocument }] =
    useInitiateDocumentPaymentMutation();
  const [redirecting, setRedirecting] = useState(false);

  const platform = () =>
    // Deep links only work inside a mobile browser; assume web otherwise.
    /Android|iPhone|iPad/i.test(navigator.userAgent) ? 'mobile' : 'web';

  /** A licence application's fee. */
  function pay(applicationId: string, provider = 'TELEBIRR'): Promise<void> {
    return handOver(() =>
      initiate({ id: applicationId, provider, platform: platform() }).unwrap(),
    );
  }

  /** A Seaman Book / BTC fee — same gateway, its own endpoint. */
  function payDocument(documentId: string, provider = 'TELEBIRR'): Promise<void> {
    return handOver(() =>
      initiateDocument({ id: documentId, provider, platform: platform() }).unwrap(),
    );
  }

  async function handOver(start: () => Promise<InitiatePaymentResult>): Promise<void> {
    try {
      const result = await start();

      const action = result.clientAction;

      if (action?.type === 'REDIRECT' && action.url) {
        setRedirecting(true);
        // Full navigation, not a router push: the destination is Telebirr.
        window.location.href = action.url;
        return;
      }

      if (action?.type === 'LAUNCH_APP') {
        notifications.show({
          color: 'blue',
          title: 'Open Telebirr',
          message: `Approve the payment in your Telebirr app${
            action.receiveCode ? ` using code ${action.receiveCode}` : ''
          }.`,
          autoClose: false,
        });
        return;
      }

      notifications.show({
        color: 'orange',
        title: 'Payment could not be started',
        message: 'The payment provider did not return a checkout link.',
      });
    } catch (err) {
      notifications.show({
        color: 'red',
        title: 'Payment could not be started',
        message: extractErrorMessage(err),
      });
    }
  }

  return { pay, payDocument, isPaying: isLoading || isLoadingDocument || redirecting };
}
