import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { fr, nlBE, enGB } from 'date-fns/locale';
import { viewConfig } from 'config/general';
import CustomDropdown from 'components/enhancers/CustomDropdown';
import moment from 'moment';
import { getContent } from 'store/utils/helper';
import FormElement from 'components/structure/FormElement';
import styleIdentifiers from './dateRangePicker.scss';
import ProjectInput from '../ProjectInput/ProjectInput';
// Import actions here

let DateRange;
if (__BROWSER__) {
  DateRange = require('react-date-range').DateRange;
  require('!style-loader!css-loader!react-date-range/dist/styles.css'); // main style file
  require('!style-loader!css-loader!react-date-range/dist/theme/default.css'); // theme css file
}

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type DateRangePickerProps = StateProps & DispatchProps & OwnProps;

const DropdownItem = props => {
  const { value, label, fieldProps } = props;

  return <ProjectInput {...fieldProps} seed="fake" value={value} label={label} />;
};

const Dropdown = CustomDropdown(DropdownItem);

const DateRangePicker = (props: DateRangePickerProps) => {
  const {
    bottomClassName,
    dropdownClassName,
    dropdown,
    forceClose,
    disabledDates,
    disabledDay,
    input,
    resetLabel,
    label,
    mapping,
    doneLabel,
    doneAction,
    onChange,
    minDate,
    maxDate,
    placeholder,
    fieldProps,
  } = props;

  const inputValue = (input && input.value) || {};

  const [close, setClose] = useState(false);
  const [frontend, setFrontend] = useState(false);

  useEffect(() => {
    setFrontend(true);
  }, []);

  const lg = useSelector((state: StoreState) => state.content.lg);
  const content = useSelector((state: StoreState) => state.content.raw);

  const closeDropdown = () => {
    setClose(true);
    setTimeout(() => setClose(false), 500);
  };

  const handleChange = dates => {
    let newValues = dates && {
      startDate: dates.startDate.toISOString(),
      endDate: dates.endDate.toISOString(),
    };

    if (mapping && dates) {
      newValues = {
        [mapping.startDate]: dates.startDate.toISOString(),
        [mapping.endDate]: dates.endDate.toISOString(),
      };
    }
    input.onChange(newValues);

    if (onChange) onChange(newValues);
  };

  const startDate = mapping ? inputValue[mapping.startDate] : inputValue.startDate;
  const endDate = mapping ? inputValue[mapping.endDate] : inputValue.endDate;

  const selectionRange = {
    startDate: startDate ? new Date(startDate) : new Date(),
    endDate: endDate ? new Date(endDate) : new Date(),
    key: 'selection',
  };

  let value;
  if (startDate && endDate)
    value = `${moment(startDate).format('DD/MM')} - ${moment(endDate).format('DD/MM')}`;
  else value = getContent(content, placeholder, lg) || placeholder || 'items.dateRange.selectDate';

  if (!frontend) return false;

  const renderRange = () => {
    return (
      <FormElement {...props} className={styles('date-range-picker')}>
        <DateRange
          locale={fr}
          disabledDay={disabledDay}
          disabledDates={disabledDates}
          onChange={i => handleChange(i.selection)}
          months={1}
          minDate={minDate && new Date(minDate)}
          maxDate={maxDate && new Date(maxDate)}
          rangeColors={[viewConfig.colors.primary]}
          color={viewConfig.colors.primary}
          ranges={[selectionRange]}
          showSelectionPreview
          direction="horizontal"
        />
        <div className={styles('bottom', bottomClassName)}>
          <div className={styles('action')} onClick={() => handleChange(null)}>
            <TextItem path={resetLabel || 'items.dateRange.reset'} />
          </div>
          {dropdown && (
            <div className={styles('action')} onClick={closeDropdown}>
              <TextItem path={doneLabel || 'items.dateRange.done'} />
            </div>
          )}
        </div>
      </FormElement>
    );
  };

  if (!DateRange) return false;

  if (dropdown) {
    return (
      <Dropdown
        className={styles('dropdown', dropdownClassName)}
        value={value}
        label={label}
        forceClose={close}
        noArrow
        decal
        fieldProps={fieldProps}
      >
        {renderRange()}
      </Dropdown>
    );
  }

  return renderRange();
};

export default DateRangePicker;
