import { createContext, useContext, useState } from 'react'
import { ErrorModalTemplate } from './ErrorModalTemplate'

interface IProps {
  content?: ({ close }: { close: () => void }) => any
  error?: any
  fallBack?: string
}

type ContextType = (props: IProps) => void

const ErrorModalContext = createContext<ContextType>(null)

export default function ErrorModalProvider({ children }) {
  const [modal, setModal] = useState({
    open: false,
    content: ({ close }) => null,
    errorMessage: null,
    type: 'String',
  })

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

  const convertMessageToTable = (message) => {
    const tableRows = message.map((element, index) => {
      return `<tr><td>${index + 1}</td><td>${element}</td></tr>`
    })
    return `<table>
    <thead>
    <tr><th>S No.</th><th>Message</th></tr>
    </thead>
    <tbody>
    ${tableRows.join('')}</tbody></table>`
  }

  const showModal = (props) => {
    const fallbackMessage = props.fallBack ?? 'Something went wrong.'
    const type =
      typeof props.error?.response?.data?.message !== 'string'
        ? 'Object'
        : 'String'
    const errorMessage =
      typeof props.error?.response?.data?.message !== 'string'
        ? convertMessageToTable(props.error?.response?.data?.message) ??
          fallbackMessage
        : props.error?.response?.data?.message

    setModal({
      ...modal,
      open: true,
      type: type,
      content: props.content,
      errorMessage: errorMessage,
    })
  }

  return (
    <ErrorModalContext.Provider value={showModal}>
      {children}
      <>
        <ErrorModalTemplate
          handleClose={handleClose}
          modal={modal}
          setModal={setModal}
        />
      </>
    </ErrorModalContext.Provider>
  )
}

export const useErrorModal = () => useContext(ErrorModalContext)
