/**
 * Settings data hook.
 *
 * @package RawTypeOE
 */

import { useCallback, useEffect, useState } from '@wordpress/element';
import apiFetch from '../utils/apiFetch';

const DEFAULT_SETTINGS = {
	default_format: 'csv',
	date_format: 'Y-m-d',
};

export default function useSettings() {
	const [ settings, setSettings ] = useState( DEFAULT_SETTINGS );
	const [ loading, setLoading ] = useState( true );
	const [ saving, setSaving ] = useState( false );
	const [ error, setError ] = useState( null );

	const loadSettings = useCallback( () => {
		setLoading( true );
		setError( null );

		return apiFetch( { path: '/rawtype_oe/v1/settings' } )
			.then( ( data ) => {
				setSettings( {
					...DEFAULT_SETTINGS,
					...data,
				} );
				setLoading( false );
				return data;
			} )
			.catch( ( requestError ) => {
				setError( requestError );
				setLoading( false );
				throw requestError;
			} );
	}, [] );

	useEffect( () => {
		loadSettings().catch( () => {} );
	}, [ loadSettings ] );

	const saveSettings = useCallback( ( nextSettings ) => {
		setSaving( true );
		setError( null );

		return apiFetch( {
			path: '/rawtype_oe/v1/settings',
			method: 'POST',
			data: {
				default_format: nextSettings.default_format,
				date_format: nextSettings.date_format,
			},
		} )
			.then( ( data ) => {
				setSettings( {
					...DEFAULT_SETTINGS,
					...data,
				} );
				setSaving( false );
				return data;
			} )
			.catch( ( requestError ) => {
				setError( requestError );
				setSaving( false );
				throw requestError;
			} );
	}, [] );

	return {
		settings,
		setSettings,
		loading,
		saving,
		error,
		loadSettings,
		saveSettings,
	};
}
