import { Box, Button, Modal as ModalMui, Typography } from '@mui/material'
import {
  Link,
  matchPath,
  Outlet,
  useLocation,
  useNavigate
} from 'react-router-dom'
import styles from './style.module.scss'
import { appPublicRoutes } from '../../routes'

function useRouteMatch(patterns: readonly string[]) {
  const { pathname } = useLocation()

  for (let i = 0; i < patterns.length; i += 1) {
    const pattern = patterns[i]
    const possibleMatch = matchPath(pattern, pathname)
    if (possibleMatch !== null) {
      return possibleMatch
    }
  }

  return null
}

export const Modal = () => {
  const navigate = useNavigate()
  const tabs = [
    { to: appPublicRoutes.login, title: 'Login', label: 'Login' },
    { to: appPublicRoutes.register, title: 'Register', label: 'Register' },
    { to: appPublicRoutes.nostr, title: 'Login', label: <>Ostrich</> }
  ]
  const routeMatch = useRouteMatch(tabs.map((t) => t.to))
  const activeTab = routeMatch?.pattern?.path
  const handleClose = () => {
    navigate(appPublicRoutes.landingPage)
  }

  return (
    <ModalMui
      open={true}
      onClose={handleClose}
      aria-labelledby="modal-title"
      aria-describedby="modal-description"
    >
      <Box className={styles.modal}>
        <Typography id="modal-title" variant="h2">
          {tabs.find((t) => activeTab === t.to)?.title}
        </Typography>

        <Box component={'ul'}>
          {tabs.map((t) => {
            return (
              <Button
                component={Link}
                to={t.to}
                key={t.to}
                variant={
                  activeTab === t.to || t.to === appPublicRoutes.nostr
                    ? 'contained'
                    : 'text'
                }
              >
                {t.label}
              </Button>
            )
          })}
        </Box>

        <Outlet />

        <Typography id="modal-description" variant="h4">
          Welcome to Sigit
        </Typography>
      </Box>
    </ModalMui>
  )
}
