/**
 * WordPress dependencies
 */
import apiFetch from '@safe-wordpress/api-fetch';
import { useState } from '@safe-wordpress/element';

/**
 * Internal dependencies
 */
import './style.scss';
import { useValue } from '../hooks';
import { openConnectionAuthorizer } from './utils';
import { Connection } from './connection';
import type { ConnectionMode, GA4Property } from './config';
import type { FieldSettingProps } from '../types';

export const GoogleAnalyticsSetting = ( {
	name,
}: FieldSettingProps ): JSX.Element => {
	const [ properties, setProperties ] = useState<
		ReadonlyArray< GA4Property >
	>( [] );

	const [ property, setProperty ] = useValue< GA4Property >( name );

	const [ mode, setMode ] = useState< ConnectionMode >(
		!! property?.id ? 'ga4-property-id' : 'init'
	);

	const connectAccount = () =>
		openConnectionAuthorizer( {
			onOpen: () => {
				setMode( 'awaiting-authorization' );
			},
			onClose: () => {
				setMode( 'property-retrieval' );
				void apiFetch< GA4Property[] >( {
					path: '/nelio-content/v1/analytics/ga4-properties',
				} )
					.then( ( foundProperties ) => {
						setProperties( foundProperties );
						const firstProp = foundProperties[ 0 ];
						if ( firstProp ) {
							setProperty( firstProp );
						}
						setMode( 'property-selection' );
					} )
					.catch( ( error ) => {
						// eslint-disable-next-line no-console
						console.log( error );
						setProperty( { id: '', name: '' } );
						setMode( 'init' );
					} );
			},
		} );

	const selectProperty = ( p: GA4Property ) => setProperty( p );

	return (
		<>
			<Connection
				className="nelio-content-google-analytics-setting"
				name={ name }
				mode={ mode }
				selectedProperty={ property }
				properties={ properties }
				onChangeAccount={ connectAccount }
				onSelectProperty={ selectProperty }
				currentProperty={ property }
			/>
			<input
				type="hidden"
				name={ name }
				value={ JSON.stringify( property ?? { id: '', name: '' } ) }
			/>
		</>
	);
};
