'use client'

import {useEffect, useState, useMemo} from 'react'
import {useRouter} from 'next/navigation'
import TextField from '@mui/material/TextField'
import Autocomplete from '@mui/material/Autocomplete'
import Avatar from '@mui/material/Avatar'
import Container from '@mui/material/Container'

import {jwennToutAwtis} from '../../lib/oki-api'
import {formatKuveti} from '../../lib/kuveti'

const IMAGE_URL = process.env.NEXT_PUBLIC_API_URL_ROOT || 'http://localhost:1337'

export default function ChecheAwtis() {
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const [options, setOptions] = useState([])
  const loading = open && options.length === 0

  useEffect(() => {
    let active = true

    if (!loading) {
      return undefined
    }

    (async () => {
      try {
        const {data} = await jwennToutAwtis()

        const filteredData = data.map(artiste => {
          const firstLetter = artiste.alias[0].toUpperCase()
          return {
            firstLetter: /\d/.test(firstLetter) ? '0-9' : firstLetter,
            ...artiste
          }
        })
        if (active) {
          setOptions([...filteredData])
        }
      } catch (error) {
        console.log('⚠️  Erreur', error.message)
      }
    })()

    return () => {
      active = false
    }
  }, [loading])

  const sortedOptions = useMemo(() => [...options].sort((a, b) =>
    -b.firstLetter.localeCompare(a.firstLetter)
  ), [options])

  return (
    <Container
      sx={{display: 'flex', justifyContent: 'center', marginBottom: 3}}
    >
      <Autocomplete
        autoHighlight
        disableClearable
        disableCloseOnSelect
        loading={loading}
        open={open}
        loadingText='Chargement...'
        noOptionsText='Aucun résultat'
        id='cheche-awtis'
        options={sortedOptions}
        groupBy={option => option?.firstLetter}
        getOptionLabel={option => option?.alias}
        renderOption={(optionProps, option) => {
          const {key, ...rest} = optionProps

          return (
            <li key={key} {...rest}>
              <Avatar
                style={{marginRight: 8}}
                alt={option?.alias}
                src={`${IMAGE_URL}${formatKuveti(option?.photo, 'thumbnail')?.url || ''}`}
              />
              {option?.alias}
            </li>
          )
        }}
        sx={{width: 300}}
        renderInput={params => (
          <TextField
            {...params}
            label='Rechercher un artiste'
            slotProps={{
              ...params.slotProps,
              htmlInput: {...params.slotProps.htmlInput},
            }}
          />
        )}
        onChange={(event, newValue) => {
          router.push(`/awtis/${newValue.slug}`)
        }}
        onOpen={() => setOpen(true)}
        onClose={() => setOpen(false)}
      />
    </Container>
  )
}
