<script setup>
import Section from "./Section.vue";
import EditableInput from "./EditableInput.vue";
import { useFormBuilderStore } from "../store";
import { sectionBoilerplate, confirmDialog, isTouchScreenDevice } from "../utils";
import draggable from "vuedraggable";
import { ref, computed, inject } from "vue";
import { useMagicKeys, whenever } from "@vueuse/core";
import { Icon } from '@iconify/vue';
import { t } from '@/shared/i18n';

const store = useFormBuilderStore();

// delete/backspace to delete the field
const { Backspace } = useMagicKeys();
whenever(Backspace, (value) => {
  if (value && selected.value && store.notUsingInput) {
    removeTab(store.currentTab, "", true);
  }
});

const dragged = ref(false);
const selected = computed(() => store.selected(store.currentTab?.df?.name));
const hasTabs = computed(() => store.form.layout.tabs.length > 1);

// Initialize active tab
if (store.form.layout.tabs.length > 0 && !store.form.active_tab) {
  store.form.active_tab = store.form.layout.tabs[0].df.name;
}

function activateTab(tab) {
  store.activateTab(tab);
}

function dragOver(tab) {
  !dragged.value &&
    setTimeout(() => {
      store.form.active_tab = tab.df.name;
    }, 500);
}

function addNewTab() {
  store.addNewTab();
}

function addNewSection() {
  let section = sectionBoilerplate(store.getDf);
  store.currentTab.sections.push(section);
  store.form.selected_field = section.df;
}

function isTabEmpty(tab) {
  return !tab.sections.some((section) => section.columns.some((column) => column.fields.length));
}

function removeTab(tab, event, force = false) {
  if (!event?.currentTarget?.offsetParent && !force) return;

  if (store.isCustomizeForm && store.currentTab.df.is_custom_field === 0) {
    alert(t("Cannot delete standard field. You can hide it if you want"));
    throw "cannot delete standard field";
  } else if (store.hasStandardField(store.currentTab)) {
    deleteTab(tab);
  } else if (isTabEmpty(tab)) {
    deleteTab(tab, true);
  } else {
    confirmDialog(
      t("Delete Tab"),
      t("Are you sure you want to delete the tab? All the sections along with fields in the tab will be moved to the previous tab."),
      () => deleteTab(tab),
      t("Delete tab"),
      () => deleteTab(tab, true),
      t("Delete entire tab with fields")
    );
  }
}

function deleteTab(tab, withChildren) {
  let tabs = store.form.layout.tabs;
  let index = tabs.indexOf(tab);

  if (!withChildren) {
    if (index > 0) {
      let prevTab = tabs[index - 1];
      if (!isTabEmpty(tab)) {
        prevTab.sections = [...prevTab.sections, ...tab.sections];
      }
    } else {
      tabs.unshift({
        df: store.getDf("Tab Break", "", t("Details")),
        sections: tab.sections,
        is_first: true,
      });
      index++;
    }
  }

  tabs.splice(index, 1);

  let prevTabIndex = index === 0 ? 0 : index - 1;
  store.form.active_tab = tabs[prevTabIndex].df.name;
  store.form.selected_field = null;
}
</script>

<template>
  <div class="tab-header" v-if="store.form.layout.tabs.length > 1">
    <draggable
      v-show="hasTabs"
      class="tabs"
      v-model="store.form.layout.tabs"
      group="tabs"
      :delay="isTouchScreenDevice() ? 200 : 0"
      :animation="200"
      :easing="store.getAnimation"
      item-key="id"
      :disabled="store.readOnly"
    >
      <template #item="{ element }">
        <div
          :class="['tab', store.form.active_tab === element.df.name ? 'active' : '']"
          :title="element.df.fieldname"
          :data-is-user-generated="store.isUserGeneratedField(element)"
          @click.stop="activateTab(element)"
          @dragstart="dragged = true"
          @dragend="dragged = false"
          @dragover="dragOver(element)"
        >
          <EditableInput
            :text="element.df.label"
            :placeholder="t('Tab Label')"
            v-model="element.df.label"
          />
          <button
            class="remove-tab-btn btn btn-xs"
            :title="t('Remove tab')"
            @click.stop="removeTab(element, $event)"
            :hidden="store.readOnly"
          >
            <Icon icon="mdi:close" class="icon-sm" />
          </button>
        </div>
      </template>
    </draggable>
    <div class="tab-actions" :hidden="store.readOnly">
      <button
        class="new-tab-btn btn btn-xs"
        :class="{ 'no-tabs': !hasTabs }"
        :title="t('Add new tab')"
        @click="addNewTab"
      >
        <div class="add-btn-text">
          {{ t("Add tab") }}
        </div>
      </button>
    </div>
  </div>

  <div class="tab-contents">
    <div
      class="tab-content"
      v-for="(tab, i) in store.form.layout.tabs"
      :key="i"
      :class="[store.form.active_tab === tab.df.name ? 'active' : '']"
    >
      <draggable
        class="tab-content-container"
        v-model="tab.sections"
        group="sections"
        :delay="isTouchScreenDevice() ? 200 : 0"
        :animation="200"
        :easing="store.getAnimation"
        item-key="id"
        :disabled="store.readOnly"
      >
        <template #item="{ element }">
          <Section
            :tab="tab"
            :section="element"
            :data-is-user-generated="store.isUserGeneratedField(element)"
          />
        </template>
      </draggable>
      <div class="empty-tab" :hidden="store.readOnly">
        <div v-if="hasTabs">{{ t("Drag & Drop a section here from another tab") }}</div>
        <div v-if="hasTabs">{{ t("OR") }}</div>
        <button class="btn btn-default btn-sm" @click="addNewSection">
          {{ t("Add a new section") }}
        </button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.tab-header {
  display: flex;
  justify-content: space-between;
  min-height: 42px;
  align-items: center;
  background-color: #fff;
  border-bottom: 1px solid #e5e7eb;
  padding-left: 8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;

  .tabs {
    display: flex;
    flex: 1;
    overflow-x: auto;
    width: 0px;
  }

  .tab-actions {
    margin-right: 20px;

    .btn {
      background-color: #f3f4f6;
      padding: 2px;
      margin-left: 4px;
      box-shadow: none;

      .add-btn-text {
        padding: 4px 8px;
      }

      &:hover {
        background-color: #e5e7eb;
      }
    }

    .no-tabs {
      opacity: 1;
      margin-left: 15px;
    }
  }

  .tab {
    display: flex;
    align-items: center;
    position: relative;
    padding: 10px 18px 10px 15px;
    color: #6b7280;
    min-width: max-content;
    cursor: pointer;

    &::before {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      margin: 0 12px;
      width: auto;
      border-bottom: 1px solid transparent;
    }

    &:hover::before {
      border-color: #d1d5db;
    }

    &.active {
      font-weight: 600;
      color: #111827;

      &::before {
        border-color: #3b82f6;
      }
    }

    &:hover .remove-tab-btn {
      display: block;
    }

    .remove-tab-btn {
      position: absolute;
      right: -2px;
      display: none;
      padding: 2px;
    }
  }
}

.tab-contents {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 8px;
  min-height: 70px;

  .tab-content {
    display: none;
    position: relative;

    &.active {
      display: flex;
    }

    .tab-content-container {
      flex: 1;
      min-height: 4rem;
      border-radius: 8px;
      z-index: 1;

      &:empty {
        height: 7rem;
        margin: 1rem;

        & + .empty-tab {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          position: absolute;
          top: 0;
          bottom: 0;
          gap: 5px;
          width: 100%;
          padding: 15px;

          button {
            z-index: 2;
          }
        }
      }

      & + .empty-tab {
        display: none;
      }
    }
  }
}

.icon-sm {
  width: 14px;
  height: 14px;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  font-size: 12px;
  
  &:hover {
    background-color: #f9fafb;
  }
  
  &.btn-xs {
    padding: 2px 4px;
    font-size: 11px;
  }
  
  &.btn-sm {
    padding: 4px 8px;
    font-size: 13px;
  }
  
  &.btn-default {
    background-color: #f3f4f6;
    border-color: #e5e7eb;
    
    &:hover {
      background-color: #e5e7eb;
    }
  }
}
</style>
