<template>
  <div tabindex="-1" :class="{'b-panel': !nocard, 'b-panel__collapsed': collapsed, 'b-panel__active': !collapsed, [cssClass]: cssClass}">
    <slot name="before-header"></slot>
    <div v-if="collapsed && !nocard" class="b-panel__expand" @click.stop.prevent="expandPanel">
      <itf-button v-if="closeable" icon small class="b-panel__expand_button" @click="closePanel">
        <itf-icon name="cross" />
      </itf-button>
      <a href="" class="b-panel__expand_text_container">
        <itf-icon v-if="icon" :name="icon" class="mt-2" />

        <div class="b-panel__expand_text" v-text="title"></div>
      </a>
    </div>
    <div v-if="!nocard" v-show="!collapsed" class="b-panel-header px-3 pt-3 pb-2">
      <slot name="header">
        <div class="d-flex gap-3 align-items-center" style="min-width: 0">
          <itf-button icon default class="d-md-none open-menu-button" @click="$emit('open-menu')">
            <itf-icon name="menu" new />
          </itf-button>
          <slot name="title">
            <div style="min-width: 0" class="b-panel__title fw-bold mb-0 h2 text-truncate" v-text="title"></div>
          </slot>
        </div>
        <div class="d-flex gap-1">
          <slot name="buttons"></slot>
          <template v-if="expandable">
            <itf-button v-if="!isFullSize" icon default class="b-panel__expand_button d-none d-md-block" @click="fullsizePanel">
              <itf-icon new name="expand" />
            </itf-button>
            <itf-button v-else icon default class="b-panel__expand_button d-none d-md-block" @click="collapsePanel">
              <itf-icon new name="collapse" />
            </itf-button>
          </template>
          <itf-button v-if="closeable" icon default class="b-panel__expand_button" @click="closePanel">
            <itf-icon new name="close" />
          </itf-button>
        </div>
      </slot>
    </div>
    <div v-show="!collapsed" class="b-panel-body">
      <slot></slot>
    </div>

    <template v-if="!isMobile">
      <itf-popover
        v-for="step of popoversToRender"
        :key="step.name"
        :ref="`popover-${step.name}`"
        :visible="step.isSequence ? true : step.visible"
        :locator="step.locator"
        :is-activator-highlighted="step.isActivatorHighlighted"
        :trigger="step.isSequence ? 'manual' : 'click'"
        :placement="step.placement || 'bottom'"
        custom-class="onboarding-popover"
      >
        <div>
          <div v-if="step.title" class="d-flex align-items-center gap-2 px-3 py-2 border-bottom border-secondary h6 mb-0">
            <itf-icon v-if="step.titleIcon" new :name="step.titleIcon" />
            {{ step.title }}
          </div>
          <div class="d-flex flex-column gap-3 p-3">
            <div v-if="step.html" v-html="step.html" />
            <div v-else-if="step.text">{{ step.text }}</div>
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <div v-if="step.isSequence && !step.isOutOfCount" class="py-1 px-2 rounded-3 text-white" style="background: #5981C0">
                  {{ currentDisplayStepNumber }} <span class="opacity-50">з {{ sequenceOnboardingStepsCount }}</span>
                </div>
              </div>
              <itf-button small secondary @click="onboardingStepProgress(step)">
                {{ $t('components.iveGotIt') }}
              </itf-button>
            </div>
          </div>
        </div>
      </itf-popover>
    </template>
  </div>
</template>
<style lang="scss">
.b-panel {
  --b-panel-bg: var(--bs-body-bg);
  --b-panel-color: var(--bs-body-color);
  --b-panel-box-shadow: 0px 2px 6px 0px rgba(21,23,25,.05);
  --b-panel-white: #ffffff;
  --b-panel-info: #5981c0;
  --b-panel-success: #10834e;
  --b-panel-warning: #cda277;
  --b-panel-danger: #A90B00;

  margin-left: 8px;

  display: flex;
  flex-direction: column;
  border-radius: 6px;
  margin-bottom: 8px;
  margin-right: 8px;
  margin-top: 8px;
  z-index: 0;
  background: var(--b-panel-bg);
  box-shadow: var(--b-panel-box-shadow);

  @media (max-width: 768px) {
    margin: 0;
    height: 100%;
    min-width: 0 !important;

    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  &__collapsed {
    flex-basis: 38px;
    flex-grow: 0;
    flex-shrink: 0;
    min-width: 38px;
    overflow: hidden;
    position: relative;
  }
  &__active {
    overflow-y: hidden;

    flex-basis: 0;
    flex-grow: 3;
    flex-shrink: 0;
    min-width: 490px;
  }
  &__expand {
    align-items: center;
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;
    padding-top: 2px;
    cursor: pointer;
  }
  &__expand_text_container {
    text-decoration: none;
    align-items: center;
    justify-content: start;
    display: flex;
    flex-basis: 0;
    flex-direction: column;
    flex-grow: 1;
    flex-shrink: 0;
    min-height: 0;
  }
  &__expand_text {
    min-height: 0;
    padding-bottom: 12px;
    padding-top: 12px;
    writing-mode: vertical-lr;
  }
}
.b-panel-body {
  overflow: auto;
  position: relative;
  z-index: 0;
  align-items: stretch;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.b-panel-header {
  align-items: center;
  background: var(--b-panel-bg);
  color: var(--b-panel-color);
  display: flex;
  gap: 8px;
  justify-content: space-between;
  min-height: 45px;
  min-width: 0;
  position: sticky;
  top: 0;
  z-index: 10;
}
</style>
<script>
import { Vue, Prop, Component, Watch } from 'vue-property-decorator';
import itfIcon from '@itfin/components/src/components/icon/Icon';
import itfButton from '@itfin/components/src/components/button/Button.vue';
import itfPopover from '@itfin/components/src/components/popover/Popover';

export default @Component({
  components: {
    itfIcon,
    itfButton,
    itfPopover,
  },
  directives: {
  },
  filters: {
  },
  provide() {
    return { currentPanel: this };
  }
})
class Panel extends Vue {
  @Prop(Number) index;
  @Prop() title;
  @Prop() icon;
  @Prop() payload;
  @Prop() panel;
  @Prop(String) cssClass;
  @Prop(Boolean) collapsed;
  @Prop(Boolean) closeable;
  @Prop(Boolean) isFullSize;
  @Prop(Boolean) expandable;
  @Prop(Boolean) animate;
  @Prop(Boolean) nocard;

  onboardingSteps = [];
  currentOnboardingStepIndex = 0;

  @Watch('panel.inAppOnboarding', { deep: true })
  onOnboardingDataChange() {
    this.initOnboarding();
    this.rebuildOnboardingPopovers(0);
  }

  @Watch('currentSequenceOnboardingStep', { deep: true })
  onCurrentStepChange() {
    this.$emit('onboarding-step-viewed', this.currentSequenceOnboardingStep);
  }

  mounted() {
    this.initOnboarding();
  }

  get isMobile() {
    return window.matchMedia('(max-width: 768px)').matches;
  }

  get sequenceOnboardingSteps() {
    return this.onboardingSteps?.filter(s => s.isSequence) ?? [];
  }

  get staticOnboardingSteps() {
    return this.onboardingSteps?.filter(s => !s.isSequence) ?? [];
  }

  get currentSequenceOnboardingStep() {
    return this.sequenceOnboardingSteps?.[this.currentOnboardingStepIndex];
  }

  get currentDisplayStepNumber() {
    if (!this.currentSequenceOnboardingStep) return 0;
    return this.sequenceOnboardingSteps.slice(0, this.currentOnboardingStepIndex + 1).filter(s => !s.isOutOfCount).length;
  }

  get popoversToRender() {
    const list = [...this.staticOnboardingSteps.filter(s => !s.isFinished)];
    if (this.currentSequenceOnboardingStep) list.push(this.currentSequenceOnboardingStep);
    return list;
  }

  get sequenceOnboardingStepsCount() {
    return this.sequenceOnboardingSteps.filter(s => !s.isOutOfCount).length;
  }

  openPanel(...args) {
    this.$emit('open', args);
  }

  expandPanel() {
    this.$emit('expand');
  }

  collapsePanel() {
    this.$emit('collapse');
  }

  fullsizePanel() {
    this.$emit('fullsize');
  }

  closePanel() {
    this.$emit('close');
  }

  initOnboarding() {
    this.onboardingSteps = this.panel?.inAppOnboarding?.steps ?? [];
    const firstUnfinishedIndex = this.sequenceOnboardingSteps.findIndex(s => !s.isFinished);
    this.currentOnboardingStepIndex = firstUnfinishedIndex === -1 ? this.sequenceOnboardingSteps.length : firstUnfinishedIndex;
  }

  rebuildOnboardingPopovers(refreshDelay) {
    this.popoversToRender.forEach(step => {
      const popoverRef = this.$refs[`popover-${step.name}`];
      if (popoverRef?.[0]) popoverRef[0].refresh(refreshDelay);
    });
  }

  onboardingStepProgress(step) {
    const popoverRef = this.$refs[`popover-${step.name}`];
    if (popoverRef?.[0]) popoverRef[0].hide();

    if (step.isSequence) {
      const nextUnfinishedIndex = this.sequenceOnboardingSteps.findIndex((s, index) => {
        return index > this.currentOnboardingStepIndex && !s.isFinished;
      });
      this.currentOnboardingStepIndex = nextUnfinishedIndex === -1 ? this.sequenceOnboardingSteps.length : nextUnfinishedIndex;
    }

    this.$emit('onboarding-progress', step);
  }
}
</script>
