import { useState, useEffect } from '@wordpress/element'
import { useDispatch } from '@wordpress/data'
import apiFetch from '@wordpress/api-fetch'
import { SettingsObject, SettingsSchema } from '../types/types'

export const useSettings = (settingsSchema: SettingsSchema, initialSettings: SettingsObject, postId: number | null) => {
  const [settings, setSettings] = useState<SettingsObject>(() => {
    const defaults = Object.fromEntries(
      Object.entries(settingsSchema).map(([key, setting]) => [key, setting.default])
    )

    return {
      ...defaults,
      ...initialSettings,
    }
  })
  
  const { editPost } = useDispatch('core/editor')

  useEffect(() => {
    if (!postId) return

    const fetchSettings = async () => {
      try {
        const response = await apiFetch<SettingsObject>({ path: `/easy-critical-css/v1/get-settings/${postId}` })
        setSettings(prevSettings => ({ ...prevSettings, ...response }))
      } catch (err) {
        console.error('Error fetching Easy Critical CSS settings:', err)
      }
    }

    fetchSettings()
  }, [postId])
  
  const updateSetting = (key: string, value: any) => {
    setSettings(prev => ({ ...prev, [key]: value }))

    apiFetch({
      path: `/easy-critical-css/v1/update-settings/${postId}`,
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ [key]: value }),
    }).catch(err => console.error(`Error updating ${key}:`, err))

    editPost({ meta: { [key]: value } })
  }

  return { settings, updateSetting }
}
