'use client'

import {useState} from 'react'
import Box from '@mui/material/Box'
import PropTypes from 'prop-types'
import {union, deburr} from 'lodash'
import useMediaQuery from '@mui/material/useMediaQuery'

import Divider from '@mui/material/Divider'
import FormControl from '@mui/material/FormControl'
import InputAdornment from '@mui/material/InputAdornment'
import InputBase from '@mui/material/InputBase'

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

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

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

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

    return union(filteredTitre, filteredAlias)
  }
}

export default function DrawerBar({paroles, meteEsMobilOuve}) {
  const isMobile = useMediaQuery('(max-width:600px)')
  const [search, setSearch] = useState('')

  const mizikFiltered = getMizikFiltered(paroles, search)

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

  return (
    <Box sx={{height: '100%'}}>
      <FormControl>
        <InputBase
          sx={{paddingBlock: 2}}
          placeholder='Recherche...'
          startAdornment={
            <InputAdornment position='start'>
              <SearchIcon />
            </InputAdornment>
          }
          value={search}
          onChange={handleSearch}
        />
      </FormControl>
      <Divider />
      <Box style={{marginBottom: `${isMobile ? 0 : '3em'}`, height: `calc(100% - ${isMobile ? '65px' : '115px'})`}}>
        <MizikLis
          niAwtis
          paroles={mizikFiltered}
          meteEsMobilOuve={meteEsMobilOuve}
        />
      </Box>
    </Box>
  )
}

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