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,
  ImageUploadIcon,
  InsertImage,
} from '../../../components/common/inputs/UploadInput';
import { FormFieldWrapper } from '../../../containers/form-containers/FormBuilderLayouts';
import { connect } from 'react-redux';
import {
  setActiveElement,
  editElementLabel,
  editElementDescription,
  setMinMaxChars,
  toggleAction,
  deleteFormElement,
  changeFormElement,
  uploadElementImage,
  getUploadUrl,
  removeElementImage,
  addChoiceOption,
  deleteChoiceOption,
  editOptionLabel,
  addOptionImage,
  deleteOptionImage,
  addNewLogic,
  deleteLogic,
  clearLogic,
  updateLogicProperty,
  updateLogicTarget,
  duplicateChoiceQUestion,
} from '../../../redux/action-creators/form-builder-actions/form-builder.actions';
import MultiSelectComponent from '../form-logic/MultiSelect';
import { nanoid } from 'nanoid';

const MultiChoice = ({
  setActiveElement,
  activeElement,
  serialNumber,
  elementDetails,
  editElementLabel,
  editElementDescription,
  index,
  toggleAction,
  deleteFormElement,
  uploadElementImage,
  getUploadUrl,
  changeFormElement,
  removeElementImage,
  addChoiceOption,
  deleteChoiceOption,
  editOptionLabel,
  addOptionImage,
  deleteOptionImage,
  addNewLogic,
  deleteLogic,
  clearLogic,
  updateLogicProperty,
  duplicateChoiceQUestion,
  formData,
  activePage,
}) => {
  // eslint-disable-next-line no-console
  const [uploading, setUploading] = useState(false);
  const [fileSizeError, setFileSizeError] = useState(false);
  const [uploadingOptionImage, setUploadingOptionImage] = useState('');

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

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

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

  const uploadOptionImage = async (file, index) => {
    setUploadingOptionImage(index);
    if (file.size > 300000) {
      setFileSizeError(true);
    } else {
      const uploadData = await getUploadUrl(file);
      if (uploadData?.data?.success) {
        addOptionImage(uploadData?.data?.data[0], index);
      }
    }
    setUploadingOptionImage('');
  };

  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-multi-select"></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>
                  {opt?.imageUrl?.length > 0 && (
                    <Upload
                      className="upload active"
                      style={{
                        backgroundImage: `url("${opt.imageUrl}")`,
                        backgroundRepeat: 'no-repeat',
                        backgroundPosition: 'center',
                        backgroundSize: 'cover',
                      }}
                    >
                      <svg
                        onClick={() => deleteOptionImage(i)}
                        className="cancel-upload"
                      >
                        <use href="/images/icons.svg#close"></use>
                      </svg>
                    </Upload>
                  )}
                  {!opt.imageUrl || opt?.imageUrl?.length < 1 ? (
                    <Upload className="upload">
                      {uploadingOptionImage === i ? (
                        <span className="ml-1 f-12">uploading..</span>
                      ) : (
                        <div className="d-flx-alc">
                          <ImageUploadIcon
                            onchange={file => uploadOptionImage(file, i)}
                          />
                          <span
                            className={`ml-1 f-12 ${
                              fileSizeError ? 'co-error' : ''
                            }`}
                          >
                            {fileSizeError
                              ? 'Size is larger than 300kb'
                              : 'Max size - 300kb'}
                          </span>
                        </div>
                      )}
                    </Upload>
                  ) : (
                    ''
                  )}
                  <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="py-2 border-top">
            {elementDetails.logics.length > 0 ? (
              <div>
                {elementDetails.logics.map((logic, i) => {
                  return (
                    <div key={i}>
                      <LogicWrapper className="logic-wrapper">
                        <div className="if-logic-wrapper">
                          <div className="d-flx-alc if-logic-title">
                            <div className="mr-2">
                              <CustomConditionSelect
                                value={logic.condition}
                                onChange={e =>
                                  updateLogicProperty(
                                    i,
                                    e.target.value,
                                    'condition'
                                  )
                                }
                              >
                                <option value="">condition</option>
                                <option value="equals">Equals</option>
                              </CustomConditionSelect>
                            </div>
                          </div>

                          <LogicChoice className="logic-choice pb-2">
                            <div className="">
                              <div className="mr-2">
                                <CustomLogicInputSelect
                                  value={logic.value}
                                  onChange={e =>
                                    updateLogicProperty(
                                      i,
                                      e.target.value,
                                      'value'
                                    )
                                  }
                                >
                                  <option value="">Select option</option>
                                  {elementDetails.options.map((opt, i) => {
                                    return (
                                      <option key={i} value={opt?.label}>
                                        {opt?.label}
                                      </option>
                                    );
                                  })}
                                </CustomLogicInputSelect>
                              </div>
                            </div>
                            <div className="">
                              <CustomConditionSelect
                                value={logic.action}
                                onChange={e =>
                                  updateLogicProperty(
                                    i,
                                    e.target.value,
                                    'action'
                                  )
                                }
                              >
                                <option value="">select action</option>
                                <option value="show">Show</option>
                                <option value="hide">Hide</option>
                              </CustomConditionSelect>
                            </div>
                            <div className="">
                              <MultiSelectComponent
                                elementDetails={elementDetails}
                                value={logic.targets}
                                index={i}
                                updateLogicProperty={updateLogicProperty}
                              />
                            </div>

                            <div className="d-flx-alc-jsb">
                              <span onClick={() => deleteLogic()}>
                                {' '}
                                <IconButton
                                  svg="close"
                                  className="delete-btn"
                                />
                              </span>
                            </div>
                          </LogicChoice>
                        </div>
                      </LogicWrapper>
                    </div>
                  );
                })}
                <div className="d-flx-alc">
                  <span onClick={() => clearLogic()}>
                    <PrimaryIconButton
                      title="Delete"
                      svg="delete-alt"
                      color="#61677C"
                      className="mr-2"
                    />
                  </span>

                  <span onClick={() => addNewLogic()}>
                    <PrimaryIconButton
                      title="Add new rule"
                      svg="plus-round"
                      className="primary-svg"
                      color="#61677C"
                    />
                  </span>
                </div>
              </div>
            ) : (
              <div className="d-flx-alc">
                <span onClick={() => addNewLogic()}>
                  <PrimaryIconButton
                    svg="add-box"
                    title="Add Logic to this question."
                    color="#838CA2"
                  />
                </span>
                <a href="/">Learn more about Logic </a>
              </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 ? (
              <InsertImage
                onchange={onUploadImage}
                title={!uploading ? 'Insert an image' : 'uploading...'}
                svg="insert-image"
              />
            ) : (
              ''
            )}
            <div className="d-flx-alc">
              {/* <BasicSwitch title="Add “other option”" className="mr-2" /> */}
              <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(
                    'multiChoice',
                    nanoid(),
                    formData,
                    activePage,
                    'Multi 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-multi-select"></use>
            </svg>
            <span>Q{serialNumber + 1}</span>
          </QuestionTag>
          <div className="preview-content">
            <h4>
              {elementDetails.label}{' '}
              {elementDetails.isMandatory && <span>*</span>}
            </h4>
            <p>{elementDetails.description}</p>
            <MultiChoicePrev>
              {elementDetails.options.map((item, i) => {
                return <InputSample key={i}>{item.label}</InputSample>;
              })}
            </MultiChoicePrev>
            {/* <SingleChoicePrev>
              <InputSample>Always</InputSample>
              <InputSample>Sometimes</InputSample>
              <InputSample>Never</InputSample>
            </SingleChoicePrev>
            <SingleChoiceWImagePrev className="grid mostly-3s">
              <InputSampleItem>
                <img src="/images/image.png" alt="?" />
                <div>A</div>
              </InputSampleItem>
              <InputSampleItem>
                <img src="/images/image.png" alt="?" />
                <div>A</div>
              </InputSampleItem>
            </SingleChoiceWImagePrev> */}
          </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,
  deleteFormElement,
  changeFormElement,
  uploadElementImage,
  getUploadUrl,
  removeElementImage,
  addChoiceOption,
  deleteChoiceOption,
  editOptionLabel,
  addOptionImage,
  deleteOptionImage,
  addNewLogic,
  deleteLogic,
  clearLogic,
  updateLogicProperty,
  updateLogicTarget,
  duplicateChoiceQUestion,
})(MultiChoice);

const CustomConditionSelect = styled.select`
  padding-top: 1.5rem;
  padding-bottom: 1.5rem;
  color: #6b7184;
  background: #f1f1f5;
  height: 44px;
  width: 150px;
  border: none;
  border-radius: 4px;
`;

const CustomLogicInputSelect = styled.select`
  padding-top: 1.5rem;
  padding-bottom: 1.5rem;
  color: #6b7184;
  background: #f1f1f5;
  height: 44px;
  width: 100%;
  border: none;
  border-radius: 4px;
`;

const Upload = styled.div`
  position: relative;
  border-radius: 4px;
  margin-right: 7.9rem;
  margin-left: 2.4rem;
  .cancel-upload {
    position: absolute;
    width: 15px;
    height: 15px;
    right: -5px;
    top: -5px;
    color: #d50033;
    z-index: 1;
    cursor: pointer;
    background: #fff;
  }
  &.active {
    width: 38px;
    height: 32px;
    margin-right: 6rem;
  }
`;
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 MultiChoicePrev = styled.div`
  div:before {
    content: '';
    position: absolute;
    width: 18px;
    height: 18px;
    left: 1.5rem;
    top: 50%;
    transform: translateY(-50%);
    background: #c5c9da;
    border-radius: 2px;
    transition: all 0.3s ease;
  }
`;
const LogicChoice = styled.div`
  position: relative;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;
  padding-top: 2rem;

  > * {
    &:first-child,
    &:nth-child(3n) {
      width: 32%;
    }
    &:nth-child(2n) {
      width: 16%;
    }
    &:last-child {
      width: 12%;
    }
  }
  .delete-btn {
    color: #d50033;
    svg {
      width: 20px;
      height: 20px;
    }
  }
  .add-btn {
    color: #61677c;
    svg {
      width: 20px;
      height: 20px;
    }
  }
`;

const LogicWrapper = styled.div`
  padding-left: 100px;
  position: relative;
  .if-logic-wrapper {
    padding-bottom: 5rem;
    position: relative;
    &:before {
      content: 'IF';
      width: 55px;
      height: 35px;
      background: #e8edff;
      border-radius: 2px;
      position: absolute;
      left: -100px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: var(--ff-medium);
      color: #0a1045;
      font-size: 1.4rem;
    }
    &:after {
      content: '';
      width: 1px;
      height: 100%;
      background: #e8edff;
      border-radius: 2px;
      position: absolute;
      left: -70px;
      top: 0;
    }
    .if-logic-title {
      > * {
        &:first-child {
          width: 81px;
        }
      }
    }
  }
  .then-logic-wrapper {
    position: relative;
    &:before {
      content: 'THEN';
      width: 55px;
      height: 35px;
      background: #e8edff;
      border-radius: 2px;
      position: absolute;
      left: -100px;
      top: -10px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: var(--ff-medium);
      color: #0a1045;
      font-size: 1.4rem;
    }
  }
`;

const QuestionTag = styled.div`
  background: #f9e0e0;
  padding: 0 0.85rem;
`;
