import {useState} from 'react'
import {styled} from '@mui/material/styles'
import PropTypes from 'prop-types'
import union from 'lodash.union'
import deburr from 'lodash.deburr'

import {
  Divider,
  FormControl,
  InputAdornment,
  InputBase
} from '@mui/material'

import SearchIcon from '@mui/icons-material/Search'

import MizikLis from '../awtis/mizik-lis'

const PREFIX = 'drawer-bar'

const classes = {
  toolbar: `${PREFIX}-toolbar`,
  list: `${PREFIX}-list`,
  form: `${PREFIX}-form`,
  text: `${PREFIX}-text`
}

const Root = styled('div')((
  {
    theme
  }
) => ({
  [`& .${classes.toolbar}`]: theme.mixins.toolbar,

  [`& .${classes.list}`]: {
    marginBottom: '6em'
  },

  [`& .${classes.form}`]: {
    marginLeft: theme.spacing(1)
  },

  [`& .${classes.text}`]: {
    marginBottom: '0.5em'
  }
}))

const getMizikFiltered = (teks, filter) => {
  if (teks) {
    const filteredTitre = teks.filter(({tit}) => {
      const deburredTit = deburr(tit)
      return deburredTit.toLowerCase().includes(deburr(filter.toLowerCase()))
    })

    const filteredAlias = teks.filter(({awtis}) => {
      const aliasLis = awtis.map(({alias}) => deburr(alias)).join(', ')
      return aliasLis.toLowerCase().includes(deburr(filter.toLowerCase()))
    })

    return union(filteredTitre, filteredAlias)
  }
}

export default function DrawerBar({meteEsMobilOuve, teks, anTeks}) {
  const slug = anTeks ? anTeks.slug : null

  const [search, setSearch] = useState('')
  const [slugTeksChwazi, meteSlugTeksChwazi] = useState(slug)

  const mizikFiltered = getMizikFiltered(teks, search)

  const handleSearch = event => {
    event.preventDefault()
    const value = event.target.value
    setSearch(value)
  }

  return (
    <Root className='search'>
      <FormControl className={classes.form}>
        <InputBase
          className={classes.toolbar}
          placeholder='Chèché...'
          startAdornment={
            <InputAdornment position='start'>
              <SearchIcon />
            </InputAdornment>
          }
          value={search}
          onChange={handleSearch}
        />
      </FormControl>
      <Divider />
      <div className={classes.list}>
        <MizikLis
          niAwtis
          meteEsMobilOuve={meteEsMobilOuve}
          teks={mizikFiltered}
          slugTeksChwazi={slugTeksChwazi}
          meteSlugTeksChwazi={meteSlugTeksChwazi}
        />
      </div>
    </Root>
  )
}

DrawerBar.propTypes = {
  meteEsMobilOuve: PropTypes.func,
  teks: PropTypes.array.isRequired,
  anTeks: PropTypes.object
}

DrawerBar.defaultProps = {
  meteEsMobilOuve: null,
  anTeks: null
}
