import { Store } from 'pullstate'
import { CustomDialog, LoginForm } from '../components'
import { DialogProps } from '@mui/material'
import InsititutionsDialog from '../components/Institutions'
import InsititutionsNotAssignedDialog from '../components/Institutions/InsititutionsNotAssignedDialog '

const getRootDialogContent = (
  key: string,
): (({ close, data }) => JSX.Element) => {
  switch (key) {
    case 'login':
      return ({ close, data }) => (
        <LoginForm loginUrl={data?.loginUrl} close={close} />
      )
    case 'institutions':
      return ({ close }) => <InsititutionsDialog close={close} />
    case 'institutions-not-assigned':
      return ({ close }) => <InsititutionsNotAssignedDialog />
    default:
      return () => <></>
  }
}

const initState = {
  isOpen: false,
  key: '',
  content: ({ close, data }) => <></>,
  contentData: null,
  dialogProps: null,
}

const rootModalStore = new Store(initState)

export default function RootModal() {
  const {
    isOpen,
    content: Content,
    contentData,
    dialogProps,
  } = rootModalStore.useState()

  const onClose = () => {
    rootModalStore.update((s) => {
      s.isOpen = false
      s.key = ''
      s.content = ({ close }) => <></>
    })
  }

  const dialogContent = () => (
    <Content close={dialogProps?.onClose ?? onClose} data={contentData} />
  )

  return (
    <CustomDialog
      content={dialogContent}
      onClose={dialogProps?.onClose ?? onClose}
      open={isOpen}
      dialogProps={dialogProps}
    />
  )
}

export const openRootModal = (props: {
  key: string
  contentData?: any
  dialogProps?: Omit<DialogProps, 'open'>
}) => {
  rootModalStore.update((s) => {
    s.isOpen = true
    s.key = props.key
    s.content = getRootDialogContent(props.key)
    s.contentData = props.contentData
    s.dialogProps = props.dialogProps
  })
}
