import { useEffect } from '@wordpress/element'
import { useSelect } from '@wordpress/data'
import apiFetch from '@wordpress/api-fetch'
import { SettingsObject } from '../types/types'

export const usePostSaving = (postId: number | null, settings: SettingsObject) => {
  const isSaving = useSelect((select: any) => ({
    isSaving: select('core/editor').isSavingPost(),
  }), [])
  
  useEffect(() => {
    if (isSaving) {
      console.log('Saving settings on post save:', settings)

      apiFetch({
        path: `/easy-critical-css/v1/update-settings/${postId}`,
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(settings),
      })
        .then(() => console.log(`Easy Critical CSS Settings saved with post update`))
        .catch((err) => console.error(`Error saving settings with post update:`, err))
    }
  }, [isSaving])
}
