import { format } from 'date-fns';
import React, { useMemo, useState } from 'react';
import styled from 'styled-components';
import DatePickerHeaderDropdown from './DatePickerHeaderDropdown';
import ChevronDownIcon from '../../../assets/icons/ChevronDownIcon';

type MonthOrYear = 'month' | 'year';
interface Props {
  type: MonthOrYear;
  date: Date;
  onSelect: (newValue: number) => void;
}

const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];

const generateYears = (): number[] => {
  const years: any = [];
  const currentYear = new Date().getFullYear();
  for (let i = 1990; i < currentYear + 1; i++) {
    years.push(i);
  }
  return years.reverse();
};

function MonthOrYearPicker({ type, date, onSelect }: Props) {
  const [open, setOpen] = useState(false);
  const toggle = () => setOpen(old => !old);

  const current = useMemo(() => {
    if (type === 'month') {
      return format(date, 'LLLL');
    } else if (type === 'year') {
      return format(date, 'yyyy');
    }
    return `Cannot find ${type}`;
  }, [date, type]);

  const options: string[] = useMemo(() => {
    switch (type) {
      case 'month':
        return months;
      case 'year':
        return generateYears().map(year => `${year}`);
      default:
        return [];
    }
  }, [type]);

  return (
    <Container onClick={toggle}>
      <Current>{current}</Current>
      <div>
        {' '}
        {open ? (
          <ChevronDownIcon fill="#C2C6CE" />
        ) : (
          <ChevronUpIcon fill="#C2C6CE" />
        )}{' '}
      </div>
      {open && (
        <DatePickerHeaderDropdown
          options={options}
          selected={current}
          onSelect={onSelect}
          useIndex={type === 'month'}
        />
      )}
    </Container>
  );
}

const ChevronUpIcon = styled(ChevronDownIcon)`
  transform: rotate(180deg);
  cursor: pointer;
`;

const Current = styled.span`
  color: white;
  font-weight: 500;
  font-size: 18px;
`;

const Container = styled.div`
  display: flex;
  margin-right: 20px;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.4);
  position: relative;
`;

export default MonthOrYearPicker;
