// @flow
import React, { useCallback } from 'react';
import { injectIntl } from 'react-intl';
import type { InjectIntlProvidedProps } from 'react-intl';
import styled from 'styled-components';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import type { DatepickerProps } from './datepicker.proptypes';
import { datepickerPropTypes } from './datepicker.proptypes';
import { datePickerStyles } from './datepicker.css-rules';
import type { SpaceProps } from '../../mixins/spacing/spacing.proptypes';
import { Box } from '../../primitives/box';
import { FieldLabel } from '../../core/typography/field-label';

// we put the date picker styles here so it's specific to this instance rather than globally
const StyledBox = styled(Box)`
  && {
    ${datePickerStyles};
  }
`;

type DatePickerProps = DatepickerProps & SpaceProps & InjectIntlProvidedProps;

export const Datepicker = injectIntl(
  ({
    intl,
    label,
    onChange,
    value,
    disabledDates = [],
    disableWeekends = false,
    disablePastDates = false,
    ...otherProps
  }: DatePickerProps) => {
    const formatDate = useCallback(
      () =>
        intl.formatDate(value, {
          month: 'short',
          day: 'numeric',
          year: 'numeric',
        }), // Format based on locale
      [value, intl],
    );

    const parseDate = useCallback(() => (value ? new Date(value) : undefined), [
      value,
    ]);

    const handleDayChange = useCallback(
      day => {
        onChange(day);
      },
      [onChange],
    );

    return (
      <StyledBox stacked="column" {...otherProps}>
        <FieldLabel>{label}</FieldLabel>
        <DayPickerInput
          value={value}
          onDayChange={handleDayChange}
          formatDate={formatDate}
          parseDate={parseDate}
          dayPickerProps={{
            disabledDays: [
              ...disabledDates,
              { ...(disableWeekends ? { daysOfWeek: [0, 6] } : {}) },
              { ...(disablePastDates ? { before: new Date() } : {}) },
            ],
            ...(disablePastDates ? { fromMonth: new Date() } : {}),
            showOutsideDays: true,
            enableOutsideDaysClick: true,
          }}
        />
      </StyledBox>
    );
  },
);

Datepicker.displayName = 'DatePicker';
Datepicker.propTypes = datepickerPropTypes;
