import {memo} from 'react';
import {__} from "@wordpress/i18n";
import {Button} from "@wordpress/components";
import useNoticeStore from "../stores/useNoticeStore";
import fetcher from "../../../utils/fetcher";
import localizeSettings from "../types/localizeSettings";
import useSettingsStore from "../stores/useSettingsStore";

const restUrl = localizeSettings.restUrl;
const GROUP = localizeSettings.GROUP;

const SaveChanges = () => {

	const setError = useNoticeStore(state => state.setError);
	const setSuccess = useNoticeStore(state => state.setSuccess);
	const loading = useNoticeStore(state => state.loading);
	const setLoading = useNoticeStore(state => state.setLoading);

	async function handleSave() {
		if (loading) {
			return;
		}
		try {
			setLoading(true);
			const res: any = await fetcher(`${restUrl}${GROUP}/v1/save-settings`, {
				method: "POST",
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': localizeSettings.nonce
				},
				body: JSON.stringify(useSettingsStore.getState())
			})
			setSuccess(res);
		} catch (e: any) {
			setError(e?.message || JSON.stringify(e))
		} finally {
			setLoading(false)
			window.scrollTo({
				top: 0,
				behavior: 'smooth',
			});
		}
	}

	return (
		<Button
			type={'button'}
			variant="primary"
			size={'compact'}
			onClick={handleSave}
			isBusy={loading}
			disabled={loading}
		>
			{__('Save Changes')}
		</Button>
	);
};

export default memo(SaveChanges);
