import { createTheme, ThemeProvider } from '@mui/material/styles'
import _identity from 'lodash/identity'
import _slice from 'lodash/slice'
import React, { useEffect, useState } from 'react'

import { getPreRegistrationInfluencers } from '../../api/preRegistrationComplete'
import { Influancers } from './Influancers'
import { Prewards } from './Prewards'

export const PreRegistrationInformations = (props: IPreRegistrationInformationProps) => {
  const {
    classNamePrefix,
    eventId,
    onGetPreregistrationDataSuccess = _identity,
    onGetPreregistrationDataError = _identity,
    influancersHeaderNode,
    prewardsHeaderNode,
    themeOptions,
  } = props

  const themeMui = createTheme(themeOptions)

  const [prizes, setPrizes] = useState([] as Array<IPrizeData>)
  const [influencers, setInfluencers] = useState([] as Array<IInfluencerData>)
  const topInfluancers = _slice(influencers, 0, 10)
  useEffect(() => {
    const fetchPreregistrationData = async () => {
      try {
        const preregistrationData = await getPreRegistrationInfluencers({
          eventId,
        })
        setPrizes(preregistrationData.data.attributes.prizes)
        setInfluencers(preregistrationData.data.attributes.influencers)
        onGetPreregistrationDataSuccess()
      } catch (error) {
        if (error) {
          onGetPreregistrationDataError()
        }
      }
    }
    fetchPreregistrationData()
  }, [eventId, onGetPreregistrationDataError, onGetPreregistrationDataSuccess])

  return (
    <ThemeProvider theme={themeMui}>
      <div className={`${classNamePrefix}_pre_registration_info_container`}>
        <Prewards
          headerNode={prewardsHeaderNode}
          data={prizes}
          classNamePrefix={classNamePrefix}
        />
        <Influancers
          headerNode={influancersHeaderNode}
          data={topInfluancers}
          classNamePrefix={classNamePrefix}
        />
      </div>
    </ThemeProvider>
  )
}
