import { memo, useCallback, useEffect, useState } from 'react'
import ManagedDialogsLayer from './ManagedDialogLayer';
import { dialogManagerInternal } from './dialogManager';
import { ManagedDialogDefine, ManagedDialogDict } from './types';

const ManagedDialogProvider = memo(({ children }: { children: React.ReactNode }) => {

  const [dialogDict, setDialogDict] = useState<ManagedDialogDict>({});
  const [dialogDefine, setDialogDefine] = useState<ManagedDialogDefine>({})
  const closeDialog = useCallback((type: string) => {
    setDialogDict(old => {
      const newDict = { ...old };
      delete newDict[type]
      return newDict;
    })
  }, [setDialogDict])
  useEffect(() => {
    if (dialogManagerInternal.dialogDefine) {
      setDialogDefine(dialogManagerInternal.dialogDefine);
    }
    dialogManagerInternal.initDialogDefine = setDialogDefine

    dialogManagerInternal.showDialog = ({ type, props }) => {
      setDialogDict(old => ({ ...old, [type]: props }))
    }
    dialogManagerInternal.closeDialog = closeDialog

    return () => {
      dialogManagerInternal.showDialog = undefined;
      dialogManagerInternal.closeDialog = undefined;
      dialogManagerInternal.initDialogDefine = undefined;
    }

  }, [setDialogDict, closeDialog, setDialogDefine])

  return <>
    {children}
    <ManagedDialogsLayer dialogDefine={dialogDefine} dialogs={dialogDict} closeDialog={closeDialog} />
  </>

})

export default ManagedDialogProvider