/* eslint-disable react/display-name */

import React, { useState, forwardRef } from 'react';
import DateInputComponent from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';
import moment from 'moment';
import { TextInput } from '../TextInput';
import { Button } from '../Button';
import { Flex } from '../Flex';
import { Box } from '../Box';
import * as sc from './styles';

export interface DateInputProps {
  name?: string;
  placeholder?: string;
  popperPlacement?: string;
  dateFormat?: string;
  invalid?: boolean;
  hasExpiry?: boolean;
  autoFocus?: boolean;
  noExpiryOption?: boolean;
  noExpiryCopy?: string;
  value?: any;
  onChange?: (state: any) => void;
  onBlur?: (state: any) => void;
}

const formatDate = (date: Date, dateFormat: string) =>
  moment(date).format(dateFormat);

export function DateInput({
  value,
  onChange,
  onBlur,
  autoFocus,
  placeholder = 'Date',
  dateFormat = 'MM/DD/YYYY',
  invalid,
  noExpiryOption,
  noExpiryCopy = 'No expiry',
  ...props
}: DateInputProps) {
  const isNoExpiry =
    noExpiryOption &&
    (value === undefined || value === null || value === noExpiryCopy);
  const [currentSelected, setCurrentSelected] = useState(
    isNoExpiry ? noExpiryCopy : formatDate(value, dateFormat)
  );
  const isDateSelected = currentSelected && currentSelected !== noExpiryCopy;

  const handleChange = (selectedDate: Date) => {
    const formattedDate = formatDate(selectedDate, dateFormat);
    setCurrentSelected(formattedDate);
    if (onChange) onChange(selectedDate);
  };

  const handleNoExpiry = () => {
    setCurrentSelected(noExpiryCopy);
    if (onChange) onChange(null);
  };

  return (
    <DateInputComponent
      component={forwardRef((componentProps, ref) => (
        <TextInput
          {...componentProps}
          {...{ onBlur, autoFocus, placeholder, invalid }}
          // eslint-disable-next-line
          // @ts-ignore
          inputRef={ref}
          value={currentSelected}
        />
      ))}
      overlayComponent={({ children, ...overlayProps }: any) => (
        <sc.Overlay
          borderRadius="3"
          boxShadow="2"
          borderColor="gray.4"
          border="1px solid"
          p="m"
          {...overlayProps}
        >
          <Flex flexDirection="column">
            {children}
            {noExpiryOption && (
              <Box mt="s">
                <Button variant="ghost" onClick={handleNoExpiry}>
                  {noExpiryCopy}
                </Button>
              </Box>
            )}
          </Flex>
        </sc.Overlay>
      )}
      dayPickerProps={{
        onDayClick: handleChange,
        showOutsideDays: true,
        month: isDateSelected ? new Date(currentSelected) : undefined,
        selectedDays: isDateSelected ? [new Date(currentSelected)] : undefined,
      }}
      {...props}
    />
  );
}

DateInput.displayName = 'DateInput';
