import React, { useState } from 'react';
import styled from 'styled-components';
import { ModalTabs } from '../../containers/navbar/tabs/Tabs';
import { CustomCheckBox } from '../common/inputs/Checkbox';
import { InputWOLabelAlt, RegularInput } from '../common/inputs/TextInput';
import { LabelIcon } from '../common/texts/TextIcon';
import DatePicker from 'react-date-picker';
import { useToasts } from 'react-toast-notifications';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
import { connect } from 'react-redux';
import {
  addFormDueDate,
  allowValidation,
  setNotification,
  setTotalResponse,
  setAgentResponse,
  updateDispatchName,
  shareForm,
  onAllowMultiResponse,
} from '../../redux/action-creators/form-actions/forms.actions';
import { NofillButton, PrimaryButton } from '../common/buttons/PrimaryBtn';
import { withRouter } from 'react-router-dom';

const sliderMarks = {
  100: 100,
  500: 500,
  1500: 1500,
  3000: '3000+',
};

const FormSettingsModal = props => {
  const {
    addFormDueDate,
    validation,
    setNotification,
    setTotalResponse,
    setAgentResponse,
    allowValidation,
    formId,
    notification,
    totalExpectedResponses,
    responsePerAgent,
    updateDispatchName,
    dispatchName,
    setShareModal,
    onAllowMultiResponse,
    allowMultipleResponses,
    shareForm,
    formDueDate,
    sharedLinks,
  } = props;
  const [activeTab, setActiveTAb] = useState('general');
  const [startDate, setStartDate] = useState(new Date());
  const [sharing, setSharing] = useState(false);
  const { addToast } = useToasts();

  const onDateChange = value => {
    setStartDate(value);
    addFormDueDate(value.toISOString());
  };

  const onShareForm = async () => {
    setSharing(true);
    const shareDetails = {
      name: dispatchName,
      form: formId,
      allowValidation: validation,
    };

    if (formDueDate.length > 0) {
      shareDetails.dueDate = formDueDate;
    }
    if (JSON.stringify(allowMultipleResponses.length) > 0) {
      shareDetails.allowMultipleResponses = allowMultipleResponses;
    }
    if (notification.length > 0) {
      shareDetails.notificationFrequency = notification;
    }
    if (totalExpectedResponses > 0) {
      shareDetails.totalExpectedResponses = totalExpectedResponses;
    }
    if (responsePerAgent > 0) {
      shareDetails.responsesPerAgent = responsePerAgent;
    }

    const shareData = await shareForm(shareDetails);
    if (shareData?.success) {
      props.history.push(`/share/${formId}`);
      return shareData;
    } else {
      addToast(shareData?.error, { appearance: 'error' });
    }
    setSharing(false);
  };

  return (
    <div>
      <ModalTabs active={activeTab} setActiveTab={setActiveTAb} />
      {activeTab === 'general' && (
        <div className="modal-body py-3">
          <LabelIcon title="Set a name for this form share" svg="info" />
          <InputWOLabelAlt
            value={dispatchName}
            onchange={value => updateDispatchName(value)}
          />
          <LabelIcon
            title="Set a date to stop collecting responses"
            svg="info"
          />
          <DatePicker onChange={date => onDateChange(date)} value={startDate} />
          <div>
            <LabelIcon title="Allow Validation of Responses" svg="info" />
            <div className="flex-width-1-2">
              <CustomCheckBox
                onClick={() => allowValidation(true)}
                type="radio"
                label="yes"
                name="allow-validation"
              />
              <CustomCheckBox
                onClick={() => allowValidation(false)}
                type="radio"
                label="no"
                name="allow-validation"
              />
            </div>
          </div>
        </div>
      )}
      {activeTab === 'notification' && (
        <div className="modal-body py-3">
          <div>
            <LabelIcon title="Notify me for progress on responses" svg="info" />
            <div className="flex-width-1-2">
              <CustomCheckBox
                onClick={() => setNotification('always')}
                type="radio"
                label="Always"
                name="notification"
              />
              <CustomCheckBox
                onClick={() => setNotification('daily')}
                type="radio"
                label="daily"
                name="notification"
              />
            </div>
            <div className="flex-width-1-2">
              <CustomCheckBox
                onClick={() => setNotification('monthly')}
                type="radio"
                label="Monthly"
                name="notification"
              />
              <CustomCheckBox
                type="radio"
                onClick={() => setNotification('yearly')}
                label="Yearly"
                name="notification"
              />
            </div>
          </div>
        </div>
      )}

      {activeTab === 'responses' && (
        <div className="modal-body py-3">
          <InputSliderWrapper>
            <LabelIcon
              title="Set the total number of response that you want to collect"
              svg="info"
            />
            <div className="d-flx-alc">
              <span style={{ maxWidth: '10rem', marginRight: '2rem' }}>
                <RegularInput
                  value={totalExpectedResponses}
                  onchange={value => setTotalResponse(value)}
                />
              </span>
              <Slider
                style={{ paddingTop: '1rem', marginBottom: '1rem' }}
                min={1}
                value={totalExpectedResponses}
                onChange={value => setTotalResponse(value)}
                max={3000}
                marks={sliderMarks}
              />
            </div>
          </InputSliderWrapper>
          <InputSliderWrapper className="mt-4">
            <LabelIcon
              title="Set the total number of response you want want each agent  to collect"
              svg="info"
            />
            <div className="d-flx-alc">
              <span style={{ maxWidth: '10rem', marginRight: '2rem' }}>
                <RegularInput
                  value={responsePerAgent}
                  onchange={value => setAgentResponse(value)}
                />
              </span>
              <Slider
                style={{ paddingTop: '1rem', marginBottom: '1rem' }}
                min={1}
                value={responsePerAgent}
                onChange={value => setAgentResponse(value)}
                max={3000}
                marks={sliderMarks}
              />
            </div>
          </InputSliderWrapper>
          <div className="mt-4">
            <LabelIcon title="Allow multiple responses" svg="info" />
            <div className="flex-width-1-2">
              <CustomCheckBox
                onClick={() => onAllowMultiResponse(true)}
                type="radio"
                label="yes"
                name="responses"
              />
              <CustomCheckBox
                type="radio"
                onClick={() => onAllowMultiResponse(false)}
                label="no"
                name="responses"
              />
            </div>
          </div>
        </div>
      )}
      <div className="d-flx-alc-jfe modal-action-wrap alt-modal-footer">
        <NofillButton
          title="Skip"
          onclick={() => {
            if (
              sharedLinks &&
              sharedLinks.formShares &&
              sharedLinks.formShares.length > 0
            ) {
              props.history.push(`/share/${formId}`);
            } else {
              setShareModal(false);
            }
          }}
        />
        <PrimaryButton
          text={sharing ? ' Loading...' : 'Save Settings'}
          onclick={() => onShareForm()}
        />
      </div>
    </div>
  );
};

const mapStateToProps = state => ({
  allForms: state.forms.allForms,
  formId: state.forms.formId,
  formDueDate: state.forms.formDueDate,
  dispatchName: state.forms.dispatchName,
  validation: state.forms.validation,
  notification: state.forms.notification,
  totalExpectedResponses: state.forms.totalExpectedResponses,
  responsePerAgent: state.forms.responsePerAgent,
  allowMultipleResponses: state.forms.allowMultipleResponses,
  sharedLinks: state.forms.sharedLinks,
});

export default withRouter(
  connect(mapStateToProps, {
    addFormDueDate,
    allowValidation,
    setNotification,
    setTotalResponse,
    setAgentResponse,
    updateDispatchName,
    onAllowMultiResponse,
    shareForm,
  })(FormSettingsModal)
);

const InputSliderWrapper = styled.div`
  .input-wrapper {
    margin-bottom: 0;
  }
`;
