import { createContext, useContext, useState } from 'react'
import DialogTemplate from './DialogTemplate'
import { DrawerTemplate } from './DrawerTemplate'
import ErrorTemplate from './ErrorTemplate'

interface IProps {
  title: string
  modalType?: 'dialog' | 'drawer' | 'error'
  content: ({ close }: { close: () => void }) => any
}

type ContextType = (props: IProps) => void

const DialogContext = createContext<ContextType>(null)

export default function DialogProvider({ children }) {
  const [modal, setModal] = useState({
    title: '',
    open: false,
    content: ({ close }) => null,
    modalType: 'drawer',
  })

  const handleClose = () => {
    setModal({
      ...modal,
      open: false,
    })
  }

  const showModal = (props) => {
    setModal({
      ...modal,
      open: true,
      title: props.title,
      content: props.content,
      modalType: props.modalType ?? 'drawer',
    })
  }

  return (
    <DialogContext.Provider value={showModal}>
      {children}
      <>
        {modal.modalType == 'drawer' ? (
          <DrawerTemplate
            handleClose={handleClose}
            modal={modal}
            setModal={setModal}
          />
        ) : modal.modalType == 'dialog' ? (
          <DialogTemplate
            handleClose={handleClose}
            modal={modal}
            setModal={setModal}
          />
        ) : (
          <ErrorTemplate
            handleClose={handleClose}
            modal={modal}
            setModal={setModal}
          />
        )}
      </>
    </DialogContext.Provider>
  )
}

export const useModal = () => useContext(DialogContext)
