/**
 * WordPress dependencies
 */
import apiFetch from '@safe-wordpress/api-fetch';
import { BaseControl, CheckboxControl } from '@safe-wordpress/components';
import { useState } from '@safe-wordpress/element';
import { _x, sprintf } from '@safe-wordpress/i18n';

/**
 * Internal dependencies
 */
import './style.scss';
import { Attrs, ConnectionMode, GA4Property } from './config';

import { Connection } from './connection';
import { openConnectionAuthorizer } from './utils';

export type AiGoogleAnalyticsDataProps = {
	readonly disabled?: boolean;
	readonly attributes: Attrs;
	readonly setAttributes: ( attrs: Partial< Attrs > ) => void;
};

export const AiGoogleAnalyticsData = ( {
	disabled = false,
	attributes,
	setAttributes,
}: AiGoogleAnalyticsDataProps ): JSX.Element => {
	const { enabled, propertyId, propertyName } = attributes;

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

	const [ properties, setProperties ] = useState<
		ReadonlyArray< GA4Property >
	>( [] );

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

	const selectProperty = ( p: GA4Property ) =>
		setAttributes( {
			enabled: true,
			propertyId: p.id,
			propertyName: p.name,
		} );

	const reset = () => {
		setAttributes( {
			enabled: false,
		} );
		setMode( 'init' );
	};

	return (
		<BaseControl
			id="nab-google-analytics-data-setting"
			className="nab-google-analytics-data-setting"
			label="Google Analytics"
		>
			<CheckboxControl
				label={ sprintf(
					/* translators: %s: Nelio AI. */
					_x(
						'Include Google Analytics data to improve %s’s suggestions',
						'command',
						'nelio-ab-testing'
					),
					'Nelio AI'
				) }
				disabled={ disabled }
				checked={ enabled }
				onChange={ ( checked ) => {
					setAttributes( { enabled: checked } );
					if ( ! checked ) {
						reset();
					} else if ( ! properties.length ) {
						if ( ! propertyId ) {
							connectAccount();
						} else {
							setMode( 'ga4-property-id' );
						}
					} else {
						setMode( 'property-selection' );
					}
				} }
			/>
			<Connection
				className="nab-google-analytics-data-setting__connection"
				disabled={ disabled }
				mode={ mode }
				selectedProperty={ { id: propertyId, name: propertyName } }
				properties={ properties }
				onChangeAccount={ connectAccount }
				onSelectProperty={ selectProperty }
				currentProperty={ {
					id: propertyId,
					name: propertyName,
				} }
			/>
		</BaseControl>
	);
};
