<script lang="tsx">
import { defineComponent, ref, type PropType } from 'vue'
import { type ActionBarActionInterface } from '.'
import BlackTooltip from '../tooltips/BlackTooltip.vue'

/**
 * Панель с кнопками действий (отвязки/привязки и пр) элементов таблицы, выделенных чекбоксами
 * <ul>
 * <li><a href="https://www.figma.com/file/Q4Z4CnFx4i0qhD5fbgnPpf/%F0%9F%92%BB-%D0%94%D0%B8%D0%B7%D0%B0%D0%B9%D0%BD-%D1%81%D0%B8%D1%81%D1%82%D0%B5%D0%BC%D0%B0-ARK-SPACE?type=design&node-id=12266%3A130833&mode=dev" target="_blank">Дизайн</a></li>
 * </ul>
 */
export default defineComponent({
  props: {
    /**
     * Массив кнопок-действий на панели.
     * Содержит иконку для кнопки, текст для тултипа и функцию для действия этой кнопки.
     */
    actions: {
      type: Array as PropType<ActionBarActionInterface[]>,
      default: () => [],
    },

    /**
     * Массив выбранных элементов таблицы.
     */
    callbackValue: {
      type: Array as PropType<any[]>,
      required: true,
    },
    /**
     * Количество элементов в таблице.
     */
    itemsLength: {
      type: Number,
      default: undefined,
    },

    /**
     * Функция, срабатывающая по клику на "крестик".
     * Должна закрывать панель и снимать галочки со всех выделенных элементов.
     */
    onClose: {
      type: Function as PropType<() => void>,
      required: true,
    },
    /**
     * Текст на панели. Как правило, это счетчик типа: "Выбрано: 4 из 17".
     */
    text: {
      type: String,
      required: true,
    },
  },

  setup(props) {
    const isActionAvailable = (action: ActionBarActionInterface): boolean => {
      const { elementCount, availableForCount } = action

      return Boolean(
        (
          (!elementCount || elementCount === 'any')
          || (elementCount === 'many' && props.callbackValue?.length > 1)
          || (elementCount === 'one' && props.callbackValue?.length === 1)
          || (typeof elementCount === 'number' && props.callbackValue?.length === elementCount)
        ) && (
          (!props.itemsLength || !availableForCount || availableForCount === 'any')
          || (availableForCount === 'many' && props.itemsLength > 1)
          || (availableForCount === 'one' && props.itemsLength === 1)
          || (typeof availableForCount === 'number' && props.itemsLength === availableForCount)
        ) && (
          typeof action.condition === 'undefined' || action.condition(props.callbackValue)
        ),
      )
    }

    const isActionInProgress = ref(false)

    let abortController: AbortController | undefined

    return () => (
      <>
        {props.actions.length > 0 && (
          <div class="ark-ui-table-actions">
            <p class="ark-ui-table-actions-text">{ props.text }</p>

            <div class="ark-ui-table-actions-buttons">
              { isActionInProgress.value ? (
                <BlackTooltip text='Действие выполняется...'>
                  <div
                    class='ark-ui-table-action loader-quarter ark-ui-animation-loader'
                    style='background-color: transparent !important; border-radius: 100% !important; cursor: not-allowed !important;'
                  />
                </BlackTooltip>
              ) : (
                props.actions
                  .filter(isActionAvailable)
                  .map((action) => (
                    <BlackTooltip text={`${action.isDisabledAction && action.isDisabledAction() ? 'Недостаточно прав' : action.tooltip}`}>
                      <div
                        class={`ark-ui-table-action ${action.icon} ${action.isDisabledAction && action.isDisabledAction() ? 'disabled' : ''}`}
                        onClick={async () => {
                          if (isActionInProgress.value || !isActionAvailable(action)) return
                          isActionInProgress.value = true

                          // TODO: в текущей реализации выполняемое действие не прерывается. Необходимо подумать :/
                          // eslint-disable-next-line no-async-promise-executor
                          await new Promise(async (resolve, reject) => {
                            abortController = new AbortController()
                            abortController.signal.onabort = () => reject(new Error('Действие отменено пользователем'))

                            await action.callback(props.callbackValue)
                            resolve(true)
                          }).catch(async (e) => {
                            console.log('ActionBar: Ошибка при выполнении действия', action, e)
                            await action.onAbort?.(props.callbackValue)
                          })

                          abortController = undefined
                          isActionInProgress.value = false
                        }}
                      />
                    </BlackTooltip>
                  ))
              ) }

              <BlackTooltip text={isActionInProgress.value ? 'Отменить действие' : 'Снять выделение'}>
                <div class="ark-ui-table-actions-close" onClick={() => (
                  isActionInProgress.value ? abortController?.abort() : props.onClose()
                )}/>
              </BlackTooltip>
            </div>

          </div>
        )}
      </>
    )
  },
})
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.ark-ui-table-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #585B69;
  min-width: 552px;
  box-sizing: border-box;
  border-radius: 8px;
  color: white;
  column-gap: 36px;
  font-size: 12px;
  line-height: 18px;
  font-weight: 400;
  white-space: nowrap;
  padding: 10px 12px 10px 16px;
  z-index: $tooltip;

  .ark-ui-table-actions-text {
    margin: 0;
  }

  .ark-ui-table-actions-close {
    background: url(./assets/close.svg) center center no-repeat;
    cursor: pointer;
    height: 32px;
    width: 32px;
    margin-left: 12px;
    &:hover {
      background: url(./assets/close-white.svg) center center no-repeat;
    }
  }

  .ark-ui-table-actions-buttons {
    align-items: center;
    display: flex;
    gap: 8px;
  }

  .ark-ui-table-action {
    border-radius: 4px;
    cursor: pointer;
    height: 32px;
    transition: 0.4s;
    width: 32px;

    &.detach {
      background: url(./assets/detach.svg) center center no-repeat;
    }
    &.attach {
      background: url(./assets/attach.svg) center center no-repeat;
    }
    &.search {
      background: url(./assets/search.svg) center center no-repeat;
    }
    &.arrow-down {
      background: url(./assets/arrow-down.svg) center center no-repeat;
    }
    &.arrow-up {
      background: url(./assets/arrow-up.svg) center center no-repeat;
    }
    &.arrow-right {
      background: url(./assets/arrow-right.svg) center center no-repeat;
    }
    &.arrow-up-down {
      background: url(./assets/arrow-up-down.svg) center center no-repeat;
    }
    &.calendar {
      background: url(./assets/calendar.svg) center center no-repeat;
    }
    &.chevron-2-left {
      background: url(./assets/chevron-2-left.svg) center center no-repeat;
    }
    &.chevron-2-right {
      background: url(./assets/chevron-2-right.svg) center center no-repeat;
    }
    &.chevron-down {
      background: url(./assets/chevron-down.svg) center center no-repeat;
    }
    &.chevron-left {
      background: url(./assets/chevron-left.svg) center center no-repeat;
    }
    &.chevron-right {
      background: url(./assets/chevron-right.svg) center center no-repeat;
    }
    &.chevron-up {
      background: url(./assets/chevron-up.svg) center center no-repeat;
    }
    &.double-arrow-down {
      background: url(./assets/double-arrow-down.svg) center center no-repeat;
    }
    &.double-arrow-up {
      background: url(./assets/double-arrow-up.svg) center center no-repeat;
    }
    &.download {
      background: url(./assets/download.svg) center center no-repeat;
    }
    &.upload {
      background: url(./assets/upload.svg) center center no-repeat;
    }
    &.edit {
      background: url(./assets/edit.svg) center center no-repeat;
    }
    &.filter {
      background: url(./assets/filter.svg) center center no-repeat;
    }
    &.menu {
      background: url(./assets/menu.svg) center center no-repeat;
    }
    &.image {
      background: url(./assets/image.svg) center center no-repeat;
    }
    &.minus {
      background: url(./assets/minus.svg) center center no-repeat;
    }
    &.plus {
      background: url(./assets/plus.svg) center center no-repeat;
    }
    &.production-unit {
      background: url(./assets/production-unit.svg) center center no-repeat;
    }
    &.refresh {
      background: url(./assets/refresh.svg) center center no-repeat;
    }
    &.settings {
      background: url(./assets/settings.svg) center center no-repeat;
    }
    &.trash {
      background: url(./assets/trash.svg) center center no-repeat;
    }
    &.unit {
      background: url(./assets/unit.svg) center center no-repeat;
    }
    &.x-cross {
      background: url(./assets/x-cross.svg) center center no-repeat;
    }
    &.check {
      background: url(./assets/check.svg) center center no-repeat;
    }
    &.check-off {
      background: url(./assets/check-off.svg) center center no-repeat;
    }
    &.copy {
      background: url(./assets/copy.svg) center center no-repeat;
    }
    &.warning {
      background: url(./assets/warning.svg) center center no-repeat;
    }
    &.destructive {
      background: url(./assets/destructive.svg) center center no-repeat;
    }
    &.success {
      background: url(./assets/success.svg) center center no-repeat;
    }
    &.document {
      background: url(./assets/document.svg) center center no-repeat;
    }
    &.loader {
      background: url(./assets/loader.svg) center center no-repeat;
    }
    &.loader-quarter {
      background: url(./assets/loader-quarter.svg) center center no-repeat;
    }
    &.icon-flow-arrow {
      background: url(./assets/icon-flow-arrow.svg) center center no-repeat;
    }
    &.arrow-bend-left {
      background: url(./assets/arrow-bend-left.svg) center center no-repeat;
    }
    &.arrow-bend-right {
      background: url(./assets/arrow-bend-right.svg) center center no-repeat;
    }
    &.arrow-clockwise {
      background: url(./assets/arrow-clockwise.svg) center center no-repeat;
    }
    &.arrow-counter-clockwise {
      background: url(./assets/arrow-counter-clockwise.svg) center center no-repeat;
    }
    &.eye-open {
      background: url(./assets/eye-open.svg) center center no-repeat;
    }
    &.eye-hide {
      background: url(./assets/eye-hide.svg) center center no-repeat;
    }
    &.info {
      background: url(./assets/info.svg) center center no-repeat;
    }
    &.dots-six-vertical {
      background: url(./assets/dots-six-vertical.svg) center center no-repeat;
    }
    &.login-ad {
      background: url(./assets/login-ad.svg) center center no-repeat;
    }
    &.password-off {
      background: url(./assets/password-off.svg) center center no-repeat;
    }
    &.bucket {
      background: url(./assets/bucket.svg) center center no-repeat;
    }

    &:hover {
      background-color: rgba(39, 40, 46, 0.7);
    }

    &.disabled {
      pointer-events: none;
      opacity: 0.4;
    }
  }

  :deep(.ark-ui-tooltip-cloud) {
    left: 50% !important;
    transform: translateX(-50%);
  }

  .ark-ui-tooltip:last-child {
    :deep(.ark-ui-tooltip-cloud) {
      transform: translateX(calc(-50% + 12px));
    }
  }
}
</style>
