import { useCallback, useMemo } from 'react'

import { format } from 'date-fns'

import { parseDate } from 'helpers/parseDate'

import { WeekDay, Wrapper } from './styled'

export type Props = {
  isInitialDateHidden: boolean,
  matchDates: Array<string>,
  onDateClick: (date: string) => void,
  profileDate: string,
  selectedDate: string,
}

export const VideoDate = (props: Props) => {
  const {
    isInitialDateHidden,
    matchDates,
    onDateClick,
    profileDate,
    selectedDate,
  } = props

  const selectedDateIndex = useMemo(() => (
    matchDates.findIndex((date) => date === selectedDate)
  ), [matchDates, selectedDate])

  const lastDateIndex = matchDates.length - 1

  const initialDateIndex = useMemo(() => (
    matchDates.findIndex((date) => date === profileDate)
  ), [matchDates, profileDate])

  const currentDay = useMemo(() => (
    matchDates.length && !(isInitialDateHidden && selectedDateIndex === initialDateIndex)
      ? matchDates[selectedDateIndex]
      : null
  ), [initialDateIndex, isInitialDateHidden, matchDates, selectedDateIndex])

  const previousDay = useMemo(() => {
    if (selectedDateIndex !== 0) {
      if (isInitialDateHidden && selectedDateIndex - 1 === initialDateIndex) {
        return selectedDateIndex - 1 !== lastDateIndex ? matchDates[selectedDateIndex - 2] : null
      }
      return matchDates[selectedDateIndex - 1]
    }
    return null
  }, [initialDateIndex, isInitialDateHidden, lastDateIndex, matchDates, selectedDateIndex])

  const nextDay = useMemo(() => {
    if (selectedDateIndex !== lastDateIndex) {
      if (isInitialDateHidden && selectedDateIndex + 1 === initialDateIndex) {
        return selectedDateIndex + 1 !== lastDateIndex ? matchDates[selectedDateIndex + 2] : null
      }
      return matchDates[selectedDateIndex + 1]
    }
    return null
  }, [initialDateIndex, isInitialDateHidden, lastDateIndex, matchDates, selectedDateIndex])

  const onDayClick = (date: string) => {
    onDateClick?.(date)
  }

  const formatDate = useCallback((date: string) => (
    format(parseDate(date, 'yyyy-MM-dd'), 'MMM dd, EE')
  ), [])

  return (
    <Wrapper>
      {previousDay && (
        <WeekDay
          onClick={() => onDayClick(previousDay)}
        >{formatDate(previousDay)}
        </WeekDay>
      )}
      {currentDay && (
        <WeekDay
          isActive
        >{formatDate(currentDay)}
        </WeekDay>
      )}
      {nextDay && (
        <WeekDay
          onClick={() => onDayClick(nextDay)}
        >{formatDate(nextDay)}
        </WeekDay>
      )}
    </Wrapper>
  )
}
