import { Box, Link as HrefLink, List, ListItem, styled } from '@mui/material'
import _ from 'lodash'
import { Store } from 'pullstate'
import { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { instituitionKey, urlTenantKey } from '../../../../contexts/Providers'
import { Sitemap } from '../../../../sitemap/sitemap'
import Image from '../../../Image/Image'
import { TextField } from '../../../Input'
import { collegex, enrollx, examx, payx } from '../assets'
const isProd = process.env.NODE_ENV === 'production'

const SearchStore = new Store({
  activeLinkIndex: '',
})

const StyledListItem = styled(ListItem, {
  shouldForwardProp: (prop) => prop !== 'isActive',
})<{ isActive: boolean }>(({ theme, isActive }) => ({
  textDecoration: 'none',
  transition: 'background 0.3s ease-in-out',
  borderRadius: '6px',
  '&:hover': {
    background: theme.palette.secondary.light,
  },
  background: isActive ? theme.palette.secondary.light : 'transparent',
}))

const StyledLinkWrapper = styled(Box)(({ theme }) => ({
  '& .MuiLink-root': {
    textDecoration: 'none',
    color: theme.palette.secondary.main,
  },
}))

const RenderLink = ({ link, isActive }) => {
  const reactLinkRef = useRef(null)
  const hrefLinkRef = useRef(null)

  const getUrl = () => {
    const l = window.location
    if (process.env.NODE_ENV === 'production') {
      return `${l.protocol}://${l.hostname
        .split('.')
        .splice(1, 1, link?.item?.appKey)
        .join('.')}/${urlTenantKey}/${instituitionKey}${link?.item?.path}`
    } else {
      return `https://www.${link?.item?.appKey}.campx.dev/${urlTenantKey}/${instituitionKey}${link?.item?.path}`
    }
  }

  return (
    <StyledLinkWrapper>
      {isProd &&
      window.location.hostname.split('.')[0] === link?.item?.appKey ? (
        <Link to={link?.item?.path} ref={reactLinkRef}>
          <StyledListItem isActive={isActive}>{link?.title}</StyledListItem>
        </Link>
      ) : (
        <HrefLink href={getUrl()} ref={hrefLinkRef}>
          <StyledListItem isActive={isActive}>
            {link?.item?.title}
          </StyledListItem>
        </HrefLink>
      )}
    </StyledLinkWrapper>
  )
}
export default function SearchDialog() {
  const [results, setResults] = useState(null)
  const [value, setValue] = useState('')

  const handleSearch = (e) => {
    const res = Sitemap.search(e.target.value)
    setResults(
      res?.map((item) => ({
        ...item,
        url: `${window.location.origin}/${urlTenantKey}/${instituitionKey}${item?.item?.path}`,
      })),
    )
  }

  const handleClick = (linkRef) => {
    linkRef?.current?.click()
  }

  useEffect(() => {
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
      }
    })
  }, [])

  const resultsList = Object.entries(_.groupBy(results, 'item.appKey'))?.map(
    (item) => ({
      appKey: item[0],
      results: item[1],
    }),
  )

  return (
    <Box sx={{ width: '100%', padding: '20px' }}>
      <Box sx={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
        <TextField
          value={value}
          placeholder="Search (beta)"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === 'ArrowDown') {
              SearchStore.update((s) => {
                s.activeLinkIndex = '0-0'
              })
            }
          }}
          onChange={(e) => {
            setValue(e.target.value)
            handleSearch(e)
          }}
        />
      </Box>
      <Results results={resultsList} />
    </Box>
  )
}

const Results = ({ results }) => {
  const { activeLinkIndex } = SearchStore.useState((s) => s)
  return (
    <Box>
      {results?.map((item, index) => (
        <Box key={index}>
          <List subheader={<AppTitle appKey={item?.appKey} />}>
            {item?.results?.map((linkObj, childIndex) => (
              <RenderLink
                link={linkObj}
                key={childIndex}
                isActive={`${index}-${childIndex}` === activeLinkIndex}
              />
            ))}
          </List>
        </Box>
      ))}
    </Box>
  )
}

const AppTitle = ({ appKey }) => {
  return (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'center',
        gap: '20px',
        margin: '14px 0',
      }}
    >
      <Image
        alt={appKey}
        height={20}
        width={'auto'}
        src={appListMap[appKey] ?? appListMap.ums}
      />
      <Box
        sx={{
          flexGrow: 1,
          borderBottom: (theme) => theme.borders.grayLight,
        }}
      ></Box>
    </Box>
  )
}

const appListMap = {
  ums: collegex,
  enroll: enrollx,
  exams: examx,
  payments: payx,
}
