import React, { useState } from 'react';
import styled from 'styled-components';
import FadeIn from 'react-fade-in';
import {
  IconButton,
  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,
  addChoiceOption,
  deleteChoiceOption,
  editOptionLabel,
  addOptionImage,
  deleteOptionImage,
  duplicateChoiceQUestion,
} from '../../../redux/action-creators/form-builder-actions/form-builder.actions';
import { nanoid } from 'nanoid';

const DropDownElement = ({
  setActiveElement,
  activeElement,
  serialNumber,
  elementDetails,
  editElementLabel,
  editElementDescription,
  index,
  toggleAction,
  deleteFormElement,
  uploadElementImage,
  getUploadUrl,
  changeFormElement,
  removeElementImage,
  addChoiceOption,
  deleteChoiceOption,
  editOptionLabel,
  duplicateChoiceQUestion,
  formData,
  activePage,
}) => {
  const [uploading, setUploading] = useState(false);

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

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

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

  const onUploadImage = async file => {
    setUploading(true);
    const uploadData = await getUploadUrl(file);
    if (uploadData?.data?.success) {
      uploadElementImage(uploadData?.data?.data[0]);
    }
    setUploading(false);
  };

  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-dropdown"></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="mb-2">
            {elementDetails.options.map((opt, i) => {
              return (
                <Option key={i} className="d-flx-alc">
                  <div className="space-control inputwo-label-wrap">
                    <InputWOLabel
                      value={opt?.label}
                      onchange={value => editOptionLabel(value, i)}
                      placeholder="Option"
                    />
                  </div>

                  <span onClick={() => deleteChoiceOption(i)}>
                    <IconButton svg="close" className="delete-btn" />
                  </span>
                </Option>
              );
            })}
            <span onClick={() => addChoiceOption()}>
              <PrimaryIconButton
                svg="add-box"
                title="Add new option"
                color="#838CA2"
              />
            </span>
          </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 ? (
              <InsertImage
                onchange={onUploadImage}
                title={!uploading ? 'Insert an image' : 'uploading...'}
                svg="insert-image"
              />
            ) : (
              ''
            )}
            <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={() =>
                  duplicateChoiceQUestion(
                    'dropDown',
                    nanoid(),
                    formData,
                    activePage,
                    'Single choice',
                    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-dropdown"></use>
            </svg>
            <span>Q{serialNumber + 1}</span>
          </QuestionTag>
          <div className="preview-content">
            <h4>
              {elementDetails.label}{' '}
              {elementDetails.isMandatory && <span>*</span>}
            </h4>
            <p>{elementDetails.description}</p>
            <SingleChoicePrev>
              {elementDetails.options.map((item, i) => {
                return <InputSample key={i}>{item.label}</InputSample>;
              })}
            </SingleChoicePrev>
          </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,
  addChoiceOption,
  deleteChoiceOption,
  editOptionLabel,
  addOptionImage,
  deleteOptionImage,
  duplicateChoiceQUestion,
})(DropDownElement);

const Option = styled.div`
  margin-bottom: 2.4rem;
  .space-control {
    min-width: 444px;
    .upload {
      margin-left: 4rem;
    }
  }
  .delete-btn {
    color: #d50033;
    svg {
      width: 20px;
      height: 20px;
    }
  }
`;

const InputSample = styled.div`
  background: #f7f7f8;
  height: 44px;
  margin-top: 2rem;
  border-radius: 4px;
  border-bottom: 2px solid #c5c9da;
  position: relative;
  padding: 1.2rem;
  padding-left: 50px;
  color: #61677c;
  font-size: 16px;
  font-family: var(--ff-medium);
`;
const SingleChoicePrev = styled.div`
  div:before {
    content: '';
    position: absolute;
    width: 22px;
    height: 22px;
    left: 1.5rem;
    top: 50%;
    transform: translateY(-50%);
    background: #c5c9da;
    border-radius: 50%;
    transition: all 0.3s ease;
  }
`;
const QuestionTag = styled.div`
  background: #dee4f5;
  padding: 0 0.85rem;
`;
