import { Fragment } from 'react'

import map from 'lodash/map'

import { OutsideClick } from 'features/OutsideClick'
import { BodyBackdrop } from 'features/PageLayout'
import { Icon } from 'features/Icon'

import { useDateFilter } from './hooks'
import { DatePicker } from '../DatePicker'
import {
  Wrapper,
  MonthWrapper,
  WeekDaysWrapper,
  ArrowButton,
  Arrow,
  DateButton,
  MonthYear,
  Week,
  WeekDay,
  WeekName,
  WeekNumber,
} from './styled'

import { useHeaderFiltersStore } from '../../store'

export const DateFilter = () => {
  const {
    close,
    date,
    isOpen,
    onDateChange,
    onNextClick,
    onPreviousClick,
    onWeekDayClick,
    openDatePicker,
    selectedDate,
    week,
  } = useDateFilter()

  const {
    resetFilters,
  } = useHeaderFiltersStore()

  return (
    <Wrapper>
      <MonthWrapper>
        <MonthYear onClick={openDatePicker}>
          {date.month} {' '} {date.year}
        </MonthYear>
        <DateButton isActive={isOpen} onClick={openDatePicker}>
          <Icon refIcon='Calendar' color='#fff' />
        </DateButton>
      </MonthWrapper>

      <WeekDaysWrapper>
        <ArrowButton
          aria-label='Previous week'
          onClick={onPreviousClick}
        >
          <Arrow direction='left' />
        </ArrowButton>
        <Week>
          {
            map(week, (day) => (
              <WeekDay
                key={day.name}
                selected={day.date.getDate() === selectedDate.getDate()}
                onClick={() => {
                  if (day.date.getDate() !== selectedDate.getDate()) {
                    onWeekDayClick(day.date)
                  } else {
                    resetFilters()
                  }
                }}
              >
                <WeekName>{day.name.slice(0, 3)}</WeekName>
                <WeekNumber>{day.date.getDate()}</WeekNumber>
              </WeekDay>
            ))
          }
        </Week>
        <ArrowButton
          aria-label='Next week'
          onClick={onNextClick}
        >
          <Arrow direction='right' />
        </ArrowButton>
      </WeekDaysWrapper>
      {
        isOpen && (
          <Fragment>
            <OutsideClick onClick={close}>
              <DatePicker
                open
                selected={selectedDate}
                onChange={onDateChange}
              />
            </OutsideClick>
            <BodyBackdrop />
          </Fragment>
        )
      }
    </Wrapper>
  )
}
