'use client'

import React from 'react'
import PropTypes from 'prop-types'
import {useParams} from 'next/navigation'
import {GroupedVirtuoso} from 'react-virtuoso'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import ListSubheader from '@mui/material/ListSubheader'

import {groupBy} from 'lodash'
import {formatKuveti} from '../../lib/kuveti'
import MizikLyen from './mizik-lyen'

function grupPawol(pawol) {
  const pawolTrie = pawol.sort((a, b) => a.titre.localeCompare(b.titre, 'fr', {sensitivity: 'base'}))
  const grupPawol = groupBy(pawol, anPawol => anPawol.titre[0].toUpperCase())
  const grupCounts = Object.values(grupPawol).map(anPawol => anPawol.length)
  const grup = Object.keys(grupPawol)
  grup.sort((a, b) => a[0].localeCompare(b[0], 'fr', {sensitivity: 'base'}))

  return {pawol: pawolTrie, grupCounts, grup}
}

export default function MizikLis({niAwtis, paroles, meteEsMobilOuve}) {
  const params = useParams()
  const {pawol, grupCounts, grup} = grupPawol(paroles)

  return (
    <GroupedVirtuoso
      groupCounts={grupCounts}
      components={MUIComponents}
      groupContent={index => <div>{grup[index]}</div>}
      itemContent={index => {
        const anPawol = pawol[index]
        const {couverture} = anPawol
        const kuvetiFormat = formatKuveti(couverture, 'thumbnail')

        return (
          <MizikLyen niAwtis={niAwtis} anPawol={anPawol} kuveti={kuvetiFormat} slug={params.slug} meteEsMobilOuve={meteEsMobilOuve} />
        )
      }}
    />
  )
}

const MUIComponents = {
  List: React.forwardRef(({style, children}, listRef) => (
    <List ref={listRef} style={{padding: 0, ...style, margin: 0}} component='div'>
      {children}
    </List>
  )),

  Item: ({children, ...props}) => (
    <ListItem component='div' {...props} style={{margin: 0, paddingInline: 0}}>
      {children}
    </ListItem>
  ),

  Group: ({children, style, ...props}) => (
    <ListSubheader
      component='div'
      {...props}
      style={{
        ...style,
        backgroundColor: 'transparent',
        margin: 0,
        paddingLeft: 5,
        fontWeight: 'bold'
      }}
    >
      {children}
    </ListSubheader>
  )
}

MizikLis.propTypes = {
  niAwtis: PropTypes.bool,
  paroles: PropTypes.array.isRequired,
  meteEsMobilOuve: PropTypes.func.isRequired
}

MUIComponents.List.propTypes = {
  style: PropTypes.object,
  children: PropTypes.node.isRequired,
}

MUIComponents.Item.propTypes = {
  children: PropTypes.node.isRequired,
}

MUIComponents.Group.propTypes = {
  children: PropTypes.node.isRequired,
  style: PropTypes.object,
}
