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 /*#__PURE__*/ React.createElement(
    FormFieldWrapper,
    {
      onclick: () => setActiveElement(elementDetails.unique_id),
      className: elementDetails.unique_id === activeElement ? 'active' : '',
    },
    /*#__PURE__*/ React.createElement(
      FadeIn,
      null,
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'form-field-settings',
        },
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'form-field-question mb-3',
          },
          /*#__PURE__*/ React.createElement(
            QuestionTag,
            {
              className: 'question-tag ',
            },
            /*#__PURE__*/ React.createElement(
              'svg',
              {
                className: 'bg-svg',
              },
              /*#__PURE__*/ React.createElement('use', {
                href: '/images/icons.svg#fb-multi-select',
              })
            ),
            /*#__PURE__*/ React.createElement(
              'span',
              null,
              'Q',
              serialNumber + 1
            )
          ),
          /*#__PURE__*/ React.createElement(FbQuestionInput, {
            onchange: val => editElementLabel(val),
            value: elementDetails.label,
            placeholder: 'Enter Your Question Here',
          }),
          /*#__PURE__*/ React.createElement(FbDropElement, {
            type: elementDetails.type,
            onSelect: switchElement,
          })
        ),
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'inputwo-label-wrap mb-3',
          },
          /*#__PURE__*/ React.createElement(InputWOLabel, {
            value: elementDetails.description,
            maxLength: 250,
            onchange: value => editElementDescription(value),
            placeholder: 'Add Your Description Here',
          })
        ),
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'mb-2',
          },
          elementDetails.options.map((opt, i) => {
            return /*#__PURE__*/ React.createElement(
              Option,
              {
                key: i,
                className: 'd-flx-alc',
              },
              /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'space-control inputwo-label-wrap',
                },
                /*#__PURE__*/ React.createElement(InputWOLabel, {
                  value: opt?.label,
                  onchange: value => editOptionLabel(value, i),
                  placeholder: 'Option',
                })
              ),
              opt?.imageUrl?.length > 0 &&
                /*#__PURE__*/ React.createElement(
                  Upload,
                  {
                    className: 'upload active',
                    style: {
                      backgroundImage: `url("${opt.imageUrl}")`,
                      backgroundRepeat: 'no-repeat',
                      backgroundPosition: 'center',
                      backgroundSize: 'cover',
                    },
                  },
                  /*#__PURE__*/ React.createElement(
                    'svg',
                    {
                      onClick: () => deleteOptionImage(i),
                      className: 'cancel-upload',
                    },
                    /*#__PURE__*/ React.createElement('use', {
                      href: '/images/icons.svg#close',
                    })
                  )
                ),
              !opt.imageUrl || opt?.imageUrl?.length < 1
                ? /*#__PURE__*/ React.createElement(
                    Upload,
                    {
                      className: 'upload',
                    },
                    uploadingOptionImage === i
                      ? /*#__PURE__*/ React.createElement(
                          'span',
                          {
                            className: 'ml-1 f-12',
                          },
                          'uploading..'
                        )
                      : /*#__PURE__*/ React.createElement(
                          'div',
                          {
                            className: 'd-flx-alc',
                          },
                          /*#__PURE__*/ React.createElement(ImageUploadIcon, {
                            onchange: file => uploadOptionImage(file, i),
                          }),
                          /*#__PURE__*/ React.createElement(
                            'span',
                            {
                              className: `ml-1 f-12 ${
                                fileSizeError ? 'co-error' : ''
                              }`,
                            },
                            fileSizeError
                              ? 'Size is larger than 300kb'
                              : 'Max size - 300kb'
                          )
                        )
                  )
                : '',
              /*#__PURE__*/ React.createElement(
                'span',
                {
                  onClick: () => deleteChoiceOption(i),
                },
                /*#__PURE__*/ React.createElement(IconButton, {
                  svg: 'close',
                  className: 'delete-btn',
                })
              )
            );
          }),
          /*#__PURE__*/ React.createElement(
            'span',
            {
              onClick: () => addChoiceOption(),
            },
            /*#__PURE__*/ React.createElement(PrimaryIconButton, {
              svg: 'add-box',
              title: 'Add new option',
              color: '#838CA2',
            })
          )
        ),
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'py-2 border-top',
          },
          elementDetails.logics.length > 0
            ? /*#__PURE__*/ React.createElement(
                'div',
                null,
                elementDetails.logics.map((logic, i) => {
                  return /*#__PURE__*/ React.createElement(
                    'div',
                    {
                      key: i,
                    },
                    /*#__PURE__*/ React.createElement(
                      LogicWrapper,
                      {
                        className: 'logic-wrapper',
                      },
                      /*#__PURE__*/ React.createElement(
                        'div',
                        {
                          className: 'if-logic-wrapper',
                        },
                        /*#__PURE__*/ React.createElement(
                          'div',
                          {
                            className: 'd-flx-alc if-logic-title',
                          },
                          /*#__PURE__*/ React.createElement(
                            'div',
                            {
                              className: 'mr-2',
                            },
                            /*#__PURE__*/ React.createElement(
                              CustomConditionSelect,
                              {
                                value: logic.condition,
                                onChange: e =>
                                  updateLogicProperty(
                                    i,
                                    e.target.value,
                                    'condition'
                                  ),
                              },
                              /*#__PURE__*/ React.createElement(
                                'option',
                                {
                                  value: '',
                                },
                                'condition'
                              ),
                              /*#__PURE__*/ React.createElement(
                                'option',
                                {
                                  value: 'equals',
                                },
                                'Equals'
                              )
                            )
                          )
                        ),
                        /*#__PURE__*/ React.createElement(
                          LogicChoice,
                          {
                            className: 'logic-choice pb-2',
                          },
                          /*#__PURE__*/ React.createElement(
                            'div',
                            {
                              className: '',
                            },
                            /*#__PURE__*/ React.createElement(
                              'div',
                              {
                                className: 'mr-2',
                              },
                              /*#__PURE__*/ React.createElement(
                                CustomLogicInputSelect,
                                {
                                  value: logic.value,
                                  onChange: e =>
                                    updateLogicProperty(
                                      i,
                                      e.target.value,
                                      'value'
                                    ),
                                },
                                /*#__PURE__*/ React.createElement(
                                  'option',
                                  {
                                    value: '',
                                  },
                                  'Select option'
                                ),
                                elementDetails.options.map((opt, i) => {
                                  return /*#__PURE__*/ React.createElement(
                                    'option',
                                    {
                                      key: i,
                                      value: opt?.label,
                                    },
                                    opt?.label
                                  );
                                })
                              )
                            )
                          ),
                          /*#__PURE__*/ React.createElement(
                            'div',
                            {
                              className: '',
                            },
                            /*#__PURE__*/ React.createElement(
                              CustomConditionSelect,
                              {
                                value: logic.action,
                                onChange: e =>
                                  updateLogicProperty(
                                    i,
                                    e.target.value,
                                    'action'
                                  ),
                              },
                              /*#__PURE__*/ React.createElement(
                                'option',
                                {
                                  value: '',
                                },
                                'select action'
                              ),
                              /*#__PURE__*/ React.createElement(
                                'option',
                                {
                                  value: 'show',
                                },
                                'Show'
                              ),
                              /*#__PURE__*/ React.createElement(
                                'option',
                                {
                                  value: 'hide',
                                },
                                'Hide'
                              )
                            )
                          ),
                          /*#__PURE__*/ React.createElement(
                            'div',
                            {
                              className: '',
                            },
                            /*#__PURE__*/ React.createElement(
                              MultiSelectComponent,
                              {
                                elementDetails: elementDetails,
                                value: logic.targets,
                                index: i,
                                updateLogicProperty: updateLogicProperty,
                              }
                            )
                          ),
                          /*#__PURE__*/ React.createElement(
                            'div',
                            {
                              className: 'd-flx-alc-jsb',
                            },
                            /*#__PURE__*/ React.createElement(
                              'span',
                              {
                                onClick: () => deleteLogic(),
                              },
                              ' ',
                              /*#__PURE__*/ React.createElement(IconButton, {
                                svg: 'close',
                                className: 'delete-btn',
                              })
                            )
                          )
                        )
                      )
                    )
                  );
                }),
                /*#__PURE__*/ React.createElement(
                  'div',
                  {
                    className: 'd-flx-alc',
                  },
                  /*#__PURE__*/ React.createElement(
                    'span',
                    {
                      onClick: () => clearLogic(),
                    },
                    /*#__PURE__*/ React.createElement(PrimaryIconButton, {
                      title: 'Delete',
                      svg: 'delete-alt',
                      color: '#61677C',
                      className: 'mr-2',
                    })
                  ),
                  /*#__PURE__*/ React.createElement(
                    'span',
                    {
                      onClick: () => addNewLogic(),
                    },
                    /*#__PURE__*/ React.createElement(PrimaryIconButton, {
                      title: 'Add new rule',
                      svg: 'plus-round',
                      className: 'primary-svg',
                      color: '#61677C',
                    })
                  )
                )
              )
            : /*#__PURE__*/ React.createElement(
                'div',
                {
                  className: 'd-flx-alc',
                },
                /*#__PURE__*/ React.createElement(
                  'span',
                  {
                    onClick: () => addNewLogic(),
                  },
                  /*#__PURE__*/ React.createElement(PrimaryIconButton, {
                    svg: 'add-box',
                    title: 'Add Logic to this question.',
                    color: '#838CA2',
                  })
                ),
                /*#__PURE__*/ React.createElement(
                  'a',
                  {
                    href: '/',
                  },
                  'Learn more about Logic '
                )
              )
        ),
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'd-flx-alc-jsb form-field-settings-footer',
          },
          elementDetails.imageUrl?.length > 0 &&
            /*#__PURE__*/ React.createElement(ElementUpload, {
              url: elementDetails.imageUrl,
              deleteImage: removeElementImage,
            }),
          !elementDetails.imageUrl || elementDetails?.imageUrl.length < 1
            ? /*#__PURE__*/ React.createElement(InsertImage, {
                onchange: onUploadImage,
                title: !uploading ? 'Insert an image' : 'uploading...',
                svg: 'insert-image',
              })
            : '',
          /*#__PURE__*/ React.createElement(
            'div',
            {
              className: 'd-flx-alc',
            },
            /*#__PURE__*/ React.createElement(BasicSwitch, {
              checked: elementDetails.isMandatory,
              title: 'Required',
              onchange: onToggleRequired,
              className: 'mr-2',
            }),
            /*#__PURE__*/ React.createElement(BasicSwitch, {
              onchange: onToggleHidden,
              checked: elementDetails.hidden,
              title: 'Hidden',
              className: 'mr-2',
            }),
            /*#__PURE__*/ React.createElement(
              'span',
              {
                onClick: () =>
                  duplicateChoiceQUestion(
                    'multiChoice',
                    nanoid(),
                    formData,
                    activePage,
                    'Multi choice',
                    elementDetails,
                    index
                  ),
              },
              /*#__PURE__*/ React.createElement(PrimaryIconButton, {
                title: 'Duplicate',
                svg: 'duplicate',
                className: 'mr-2',
                color: '#61677C',
              })
            ),
            /*#__PURE__*/ React.createElement(
              'span',
              {
                onClick: () => deleteFormElement(elementDetails.unique_id),
              },
              /*#__PURE__*/ React.createElement(PrimaryIconButton, {
                title: 'Delete',
                svg: 'delete-alt',
                color: '#61677C',
              })
            )
          )
        )
      ),
      /*#__PURE__*/ React.createElement(
        'div',
        {
          className: 'form-field-preview',
        },
        /*#__PURE__*/ React.createElement(
          QuestionTag,
          {
            className: 'question-tag',
          },
          /*#__PURE__*/ React.createElement(
            'svg',
            {
              className: 'bg-svg',
            },
            /*#__PURE__*/ React.createElement('use', {
              href: '/images/icons.svg#fb-multi-select',
            })
          ),
          /*#__PURE__*/ React.createElement('span', null, 'Q', serialNumber + 1)
        ),
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: 'preview-content',
          },
          /*#__PURE__*/ React.createElement(
            'h4',
            null,
            elementDetails.label,
            ' ',
            elementDetails.isMandatory &&
              /*#__PURE__*/ React.createElement('span', null, '*')
          ),
          /*#__PURE__*/ React.createElement(
            'p',
            null,
            elementDetails.description
          ),
          /*#__PURE__*/ React.createElement(
            MultiChoicePrev,
            null,
            elementDetails.options.map((item, i) => {
              return /*#__PURE__*/ React.createElement(
                InputSample,
                {
                  key: i,
                },
                item.label
              );
            })
          )
        )
      )
    )
  );
};

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;
`;
