import React, { useState } from 'react';
import styled from 'styled-components';
import FadeIn from 'react-fade-in';
import { PrimaryIconButton } from '../../../components/common/buttons/IconButton';
import { FbDropElement } from '../../../components/common/inputs/Select';
import { BasicSwitch } from '../../../components/common/inputs/Switch';
import {
  FbQuestionInput,
  InputWOLabel,
} from '../../../components/common/inputs/TextInput';
import {
  ElementUpload,
  InsertImage,
} from '../../../components/common/inputs/UploadInput';
import { FormFieldWrapper } from '../../../containers/form-containers/FormBuilderLayouts';
import { connect } from 'react-redux';
import {
  setActiveElement,
  editElementLabel,
  editElementDescription,
  setMinMaxChars,
  toggleAction,
  duplicateElement,
  deleteFormElement,
  changeFormElement,
  uploadElementImage,
  getUploadUrl,
  removeElementImage,
  clearMinimumCharacters,
} from '../../../redux/action-creators/form-builder-actions/form-builder.actions';
import { numbersOnly } from '../../../utils/helpers';

const LongText = ({
  setActiveElement,
  activeElement,
  serialNumber,
  elementDetails,
  editElementLabel,
  editElementDescription,
  setMinMaxChars,
  index,
  toggleAction,
  duplicateElement,
  deleteFormElement,
  uploadElementImage,
  getUploadUrl,
  changeFormElement,
  removeElementImage,
  clearMinimumCharacters,
}) => {
  const [uploading, setUploading] = useState(false);
  const [minLengthError, setMinLengthError] = useState('');
  const [uploadError, setUploadError] = useState('');
  const onChangeMinChar = value => {
    setMinMaxChars('minLength', value);
  };

  const onChangeMaxChar = value => {
    setMinMaxChars('maxLength', value);
  };

  const onToggleRequired = () => {
    toggleAction('isMandatory');
  };

  const onToggleHidden = () => {
    toggleAction('hidden');
  };

  const switchElement = type => {
    changeFormElement(type, index);
  };

  const onUploadImage = async file => {
    setUploadError('');
    if (file && file.size < 500000) {
      setUploading(true);
      const uploadData = await getUploadUrl(file);
      if (uploadData?.data?.success) {
        uploadElementImage(uploadData?.data?.data[0]);
      }
      setUploading(false);
    } else {
      setUploadError('Size is larger than 500KB');
    }
  };

  const checkMaxValue = () => {
    if (
      parseInt(elementDetails.maxLength) > 0 &&
      parseInt(elementDetails.minLength) > 0 &&
      parseInt(elementDetails.minLength) > parseInt(elementDetails.maxLength)
    ) {
      setMinLengthError("min-length can't be greater than max-length");
      clearMinimumCharacters();
    }
  };

  return (
    <FormFieldWrapper
      onclick={() => setActiveElement(elementDetails.unique_id)}
      className={elementDetails.unique_id === activeElement ? 'active' : ''}
    >
      <FadeIn>
        <div className="form-field-settings">
          <div className="form-field-question mb-3">
            <QuestionTag className="question-tag ">
              <svg className="bg-svg">
                <use href="/images/icons.svg#fb-long-text"></use>
              </svg>
              <span>Q{serialNumber + 1}</span>
            </QuestionTag>
            <FbQuestionInput
              onchange={val => editElementLabel(val)}
              value={elementDetails.label}
              placeholder="Enter Your Question Here"
            />
            <FbDropElement
              type={elementDetails.type}
              onSelect={switchElement}
            />
          </div>
          <div className="inputwo-label-wrap mb-3">
            <InputWOLabel
              value={elementDetails.description}
              maxLength={250}
              onchange={value => editElementDescription(value)}
              placeholder="Add Your Description Here"
            />
          </div>

          <div className="flx-jsb-rl">
            <p className="mr-6">Set minimum and maximum character (e.g 200)</p>
            <div className="d-flx-alc input-width mr-6">
              <p className="mr-1">Minimum character</p>
              <InputWOLabel
                onBlur={() => checkMaxValue()}
                value={elementDetails.minLength}
                onchange={value => {
                  if (numbersOnly(value) || value === '') {
                    onChangeMinChar(value);
                    setMinLengthError('');
                  }
                }}
                placeholder="Min"
                maxLength={5}
              />
              <small style={{ color: 'red' }}>{minLengthError}</small>
            </div>
            <div className="d-flx-alc input-width">
              <p className="mr-1">Maximum character</p>
              <InputWOLabel
                onBlur={() => checkMaxValue()}
                value={elementDetails.maxLength}
                onchange={value => {
                  if (numbersOnly(value) || value === '') {
                    onChangeMaxChar(value);
                    setMinLengthError('');
                  }
                }}
                placeholder="Max"
                maxLength={5}
              />
            </div>
          </div>
          <div className="d-flx-alc-jsb form-field-settings-footer">
            {elementDetails.imageUrl?.length > 0 && (
              <ElementUpload
                url={elementDetails.imageUrl}
                deleteImage={removeElementImage}
              />
            )}
            {!elementDetails.imageUrl || elementDetails?.imageUrl.length < 1 ? (
              <div>
                <InsertImage
                  onchange={onUploadImage}
                  title={
                    !uploading ? 'Insert an image (Max: 500KB)' : 'uploading...'
                  }
                  svg="insert-image"
                />
                <div>
                  {uploadError.length > 0 && (
                    <span className="ml-1 f-12 co-error">{uploadError}</span>
                  )}
                </div>
              </div>
            ) : (
              ''
            )}
            <div className="d-flx-alc">
              <BasicSwitch
                checked={elementDetails.isMandatory}
                title="Required"
                onchange={onToggleRequired}
                className="mr-2"
              />
              <BasicSwitch
                onchange={onToggleHidden}
                checked={elementDetails.hidden}
                title="Hidden"
                className="mr-2"
              />
              <span onClick={() => duplicateElement(elementDetails, index)}>
                <PrimaryIconButton
                  title="Duplicate"
                  svg="duplicate"
                  className="mr-2"
                  color="#61677C"
                />
              </span>
              <span onClick={() => deleteFormElement(elementDetails.unique_id)}>
                <PrimaryIconButton
                  title="Delete"
                  svg="delete-alt"
                  color="#61677C"
                />
              </span>
            </div>
          </div>
        </div>
        <div className="form-field-preview">
          <QuestionTag className="question-tag">
            <svg className="bg-svg">
              <use href="/images/icons.svg#fb-long-text"></use>
            </svg>
            <span>Q{serialNumber + 1}</span>
          </QuestionTag>
          <div className="preview-content">
            <h4>
              {elementDetails.label}{' '}
              {elementDetails.isMandatory && <span>*</span>}
            </h4>
            <p>{elementDetails.description}</p>
            <InputSample></InputSample>
          </div>
        </div>
      </FadeIn>
    </FormFieldWrapper>
  );
};

const mapStateToProps = state => ({
  activeElement: state.formBuilder.activeElement,
  formData: state.formBuilder.formData,
  formName: state.formBuilder.name,
  activePage: state.formBuilder.activePage,
  activeView: state.formBuilder.activeView,
});

export default connect(mapStateToProps, {
  setActiveElement,
  editElementLabel,
  editElementDescription,
  setMinMaxChars,
  toggleAction,
  duplicateElement,
  deleteFormElement,
  changeFormElement,
  uploadElementImage,
  getUploadUrl,
  removeElementImage,
  clearMinimumCharacters,
})(LongText);

const InputSample = styled.div`
  background: #f7f7f8;
  height: 44px;
  margin-top: 2rem;
  border-radius: 4px;
  border-bottom: 2px solid #c5c9da;
`;
const QuestionTag = styled.div`
  background: #d5def5;
  padding: 0 0.85rem;
`;
