import { Button, FormStatus, useFormStatus } from '@automattic/composite-checkout';
import { useShoppingCart } from '@automattic/shopping-cart';
import { Field } from '@automattic/wpcom-checkout';
import styled from '@emotion/styled';
import { useTranslate } from 'i18n-calypso';
import { useEffect, Fragment, ReactNode, useState, ChangeEvent } from 'react';
import {
getStateLabelText,
STATE_SELECT_TEXT,
} from 'calypso/components/domains/contact-details-form-fields/custom-form-fieldsets/utils';
import { StateSelect } from 'calypso/my-sites/domains/components/form';
import useCartKey from '../../use-cart-key';
import { useCachedContactDetails } from '../hooks/use-cached-contact-details';
import type { PaymentMethod, ProcessPayment } from '@automattic/composite-checkout';
// We currently only show Pix for Brazil so we hard-code the country to avoid
// asking the user twice or having to grab it from the billing information
// state.
const countryCode = 'BR';
interface PixPaymentMethodStateShape {
cardholderName: string;
state: string;
city: string;
postalCode: string;
address: string;
streetNumber: string;
phoneNumber: string;
taxpayerId: string;
}
type PixPaymentMethodKey = keyof PixPaymentMethodStateShape;
type StateSubscriber = () => void;
class PixPaymentMethodState {
data: PixPaymentMethodStateShape = {
cardholderName: '',
state: '',
city: '',
postalCode: '',
address: '',
streetNumber: '',
phoneNumber: '',
taxpayerId: '',
};
subscribers: StateSubscriber[] = [];
isTouched: boolean = false;
change = ( field: PixPaymentMethodKey, newValue: string ): void => {
this.data[ field ] = newValue;
this.isTouched = true;
this.notifySubscribers();
};
subscribe = ( callback: () => void ): ( () => void ) => {
this.subscribers.push( callback );
return () => {
this.subscribers = this.subscribers.filter( ( subscriber ) => subscriber !== callback );
};
};
notifySubscribers = (): void => {
this.subscribers.forEach( ( subscriber ) => subscriber() );
};
}
export function createPixPaymentMethod( {
submitButtonContent,
}: {
submitButtonContent: ReactNode;
} ): PaymentMethod {
const state = new PixPaymentMethodState();
return {
id: 'pix',
paymentProcessorId: 'pix',
label: ,
activeContent: ,
submitButton: ,
getAriaLabel: () => 'Pix',
};
}
function useSubscribeToEventEmitter( state: PixPaymentMethodState ) {
const [ , forceReload ] = useState( 0 );
useEffect( () => {
return state.subscribe( () => {
forceReload( ( val: number ) => val + 1 );
} );
}, [ state ] );
}
function usePrefillState( state: PixPaymentMethodState ): void {
const cartKey = useCartKey();
const { responseCart } = useShoppingCart( cartKey );
const isLoggedOut = responseCart.cart_key === 'no-user';
const { contactDetails } = useCachedContactDetails( { isLoggedOut } );
// Don't try to pre-fill if the form has been edited. (Also prevents
// infinite loops.)
if ( state.isTouched ) {
return;
}
if ( ! contactDetails ) {
return;
}
if ( contactDetails.postalCode ) {
state.change( 'postalCode', contactDetails.postalCode );
}
if ( contactDetails.city ) {
state.change( 'city', contactDetails.city );
}
if ( contactDetails.state ) {
state.change( 'state', contactDetails.state );
}
if ( contactDetails.phone ) {
state.change( 'phoneNumber', contactDetails.phone );
}
// Street number and address are separate in the Pix form but joined
// together in the tax form (where `contactDetails` comes from), so this
// attempts to split out the street number so we can prefill both fields.
// Street numbers in Brazil seem to mostly follow the street name (eg: "Av.
// Foo, 1098"), so we look for a number at the end of the address. If this
// fails, we just fill the address field and leave the street number field
// blank. Other possible examples of entries: "Av. Xavier da Foo, 1773, apt
// 1000", or "Est. Terra Foo 700 c 4", or "rua Foo Bar 1975".
if ( contactDetails.address1 ) {
const regexpForStreetNumber = /^(\D+?)[,\s]+(\d+|\d+[,\s]+\w+\s+\d+)$/;
const streetNumberSearch = contactDetails.address1.match( regexpForStreetNumber );
if ( streetNumberSearch && streetNumberSearch[ 1 ] && streetNumberSearch[ 2 ] ) {
state.change( 'address', streetNumberSearch[ 1 ] );
state.change( 'streetNumber', streetNumberSearch[ 2 ] );
} else {
state.change( 'address', contactDetails.address1 );
}
}
}
const PixFormWrapper = styled.div`
position: relative;
padding: 0 24px 24px 24px;
display: flex;
flex-direction: column;
gap: 14px;
`;
function PixForm( { state }: { state: PixPaymentMethodState } ) {
useSubscribeToEventEmitter( state );
usePrefillState( state );
const { formStatus } = useFormStatus();
const translate = useTranslate();
return (
{
state.change( 'cardholderName', value );
} }
label={ translate( 'Name' ) }
value={ state.data.cardholderName }
disabled={ formStatus !== FormStatus.READY }
/>
{
state.change( 'taxpayerId', value );
} }
label={ translate( 'CPF', {
textOnly: true,
comment: 'The taxpayer identification number for Brazil',
} ) }
value={ state.data.taxpayerId }
disabled={ formStatus !== FormStatus.READY }
/>
{
state.change( 'phoneNumber', value );
} }
label={ translate( 'Phone' ) }
value={ state.data.phoneNumber }
disabled={ formStatus !== FormStatus.READY }
/>
{
state.change( 'address', value );
} }
label={ translate( 'Address' ) }
value={ state.data.address }
disabled={ formStatus !== FormStatus.READY }
/>
{
state.change( 'streetNumber', value );
} }
label={ translate( 'Street Number' ) }
value={ state.data.streetNumber }
disabled={ formStatus !== FormStatus.READY }
/>
{
state.change( 'city', value );
} }
label={ translate( 'City' ) }
value={ state.data.city }
disabled={ formStatus !== FormStatus.READY }
/>
) => {
state.change( 'state', event.target.value );
} }
/>
{
state.change( 'postalCode', value );
} }
label={ translate( 'Postal Code' ) }
value={ state.data.postalCode }
disabled={ formStatus !== FormStatus.READY }
/>
);
}
function PixPayButton( {
disabled,
onClick,
submitButtonContent,
state,
}: {
disabled?: boolean;
onClick?: ProcessPayment;
submitButtonContent: ReactNode;
state: PixPaymentMethodState;
} ) {
const { formStatus } = useFormStatus();
// This must be typed as optional because it's injected by cloning the
// element in CheckoutSubmitButton, but the uncloned element does not have
// this prop yet.
if ( ! onClick ) {
throw new Error(
'Missing onClick prop; PixPayButton must be used as a payment button in CheckoutSubmitButton'
);
}
return (
);
}
const PixLogoWrapper = styled.div`
width: 24px;
`;
function PixLogo() {
return (
);
}
function PixLabel() {
return (
Pix
);
}