import { useEffect, useState } from 'react'
import { useFormContext, useFormState } from 'react-hook-form'
import { useDebouncedCallback } from '@mantine/hooks'
import useSubscribe from '../hooks/use-subscribe'
import { useSuperFormStore } from '../store/SuperForm.store'
import { openConfirmModal } from '../utils/openConfirmModal'

const SuperFormPersist = ({ storageKey }: { storageKey?: string | null }) => {
  // Component store State
  const [persistKey, setPersistKey] = useState<string>('')
  const { isDirty, isReady, isSubmitted } = useFormState()

  const { remote, request } = useSuperFormStore((state) => ({
    request: state.request,
    remote: state.remote,
  }))

  // Component Hooks
  const { reset, setValue } = useFormContext()

  const handleFormChange = useDebouncedCallback(({ values }) => {
    setPersistKey(() => {
      const key = `superform-persist-${storageKey?.length > 0 ? storageKey : `${remote?.tableName || 'local'}-${request}-${values[remote?.primaryKey] ?? ''}`}`

      if (!isDirty) {
        return key
      }

      window.localStorage.setItem(key, JSON.stringify(values))

      return key
    })
  }, 250)

  useSubscribe('', handleFormChange)

  // Component use Effects
  useEffect(() => {
    if (isReady && persistKey) {
      const data = window.localStorage.getItem(persistKey)
      if (!data) {
        return
      }

      if (isSubmitted) {
        window.localStorage.removeItem(persistKey)
        return
      }

      openConfirmModal(
        () => {
          reset(JSON.parse(data))
          setValue('_dirty', true, { shouldDirty: true })
        },
        () => {
          window.localStorage.removeItem(persistKey)
        },
        'Do you want to restore the previous data that was not submitted?'
      )
    }
  }, [isReady, isSubmitted, persistKey])

  return null
}

export default SuperFormPersist
