import {useState} from 'react'
import PropTypes from 'prop-types'
import union from 'lodash.union'
import deburr from 'lodash.deburr'

import {
  Divider,
  FormControl,
  InputAdornment,
  InputBase,
  makeStyles
} from '@material-ui/core'

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

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

const useStyles = makeStyles(theme => ({
  toolbar: theme.mixins.toolbar,
  list: {
    marginBottom: '6em'
  },
  form: {
    marginLeft: theme.spacing(1)
  },
  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 classes = useStyles()

  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 (
    <div 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>
    </div>
  )
}

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

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