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 = (paroles, filter) => {
  if (paroles) {
    const filteredTitre = paroles.filter(({attributes}) => {
      const deburredTit = deburr(attributes.titre)
      return deburredTit.toLowerCase().includes(deburr(filter.toLowerCase()))
    })

    const filteredAlias = paroles.filter(({attributes}) => {
      const aliasLis = attributes.artistes.data.map(({attributes}) => deburr(attributes.alias)).join(', ')
      return aliasLis.toLowerCase().includes(deburr(filter.toLowerCase()))
    })

    return union(filteredTitre, filteredAlias)
  }
}

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

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

  const mizikFiltered = getMizikFiltered(paroles, 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='Recherche...'
          startAdornment={
            <InputAdornment position='start'>
              <SearchIcon />
            </InputAdornment>
          }
          value={search}
          onChange={handleSearch}
        />
      </FormControl>
      <Divider />
      <div className={classes.list}>
        <MizikLis
          niAwtis
          meteEsMobilOuve={meteEsMobilOuve}
          paroles={mizikFiltered}
          slugTeksChwazi={slugTeksChwazi}
          meteSlugTeksChwazi={meteSlugTeksChwazi}
        />
      </div>
    </Root>
  )
}

DrawerBar.propTypes = {
  meteEsMobilOuve: PropTypes.func,
  paroles: PropTypes.array.isRequired,
  parole: PropTypes.object
}

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