import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

import apiFetch from '@wordpress/api-fetch';
import { getRegisteredGoalTypes } from './utils';

interface GetGoalsResponse {
	success: boolean;
	goals: Array< SavedGoalData >;
}

export const useSavedGoals = ( testId: string ) => {
	const [ savedGoals, setSavedGoals ] = useState( [] );
	const [ isSavedGoalsLoading, setIsSavedGoalsLoading ] = useState( true );
	const [ savedGoalsError, setSavedGoalsError ] = useState( null );

	useEffect( () => {
		apiFetch( { path: `/growthstack/v1/ab/goal/?test_id=${ testId }` } )
			.then( ( response: GetGoalsResponse ) => {
				let goalsWithGoalType: GoalWithGoalType[] | null = [];
				const goals =
					response?.goals &&
					typeof response.goals === 'object' &&
					Object.values( response.goals ).length > 0
						? response.goals
						: {};
				if ( Object.values( goals ).length > 0 ) {
					const goalTypes = getRegisteredGoalTypes();
					goalsWithGoalType = (
						Object.values( goals ) as SavedGoalData[]
					 ).map( ( goal: SavedGoalData ) => {
						let matchedGoalType: GoalType | null = null;
						// loop goal types
						if ( goalTypes !== null ) {
							for ( const [ key, goalType ] of Object.entries(
								goalTypes
							) ) {
								if ( goalType.type === goal.type ) {
									matchedGoalType = goalType;
									break;
								}
							}
						}
						const obj: {
							goal: SavedGoalData;
							goalType?: GoalType;
						} = {
							goal,
						};
						if ( matchedGoalType !== null ) {
							obj.goalType = matchedGoalType;
						}
						return obj;
					} );
				}

				setSavedGoals( goalsWithGoalType );
				setIsSavedGoalsLoading( false );
				setSavedGoalsError( null );
			} )
			.catch( ( error: any ) => {
				console.error( error );
				setIsSavedGoalsLoading( false );
				setSavedGoalsError(
					__( 'Error while loading saved goals.', 'liana-with-growthstack' )
				);
			} );
	}, [] );

	return [ savedGoals, isSavedGoalsLoading, savedGoalsError ];
};
