<template>
  <div class="page-builder overflow-auto">
    <div class="flex gap-4 px-6 overflow-auto">
      <div class="flex w-[356px] flex-col gap-2 pb-10 overflow-y-auto h-[100vh]">
        <div v-for="(parent, sectionIndex) in modelValue.sections" class="border-b border-gray-200 pb-2">
          <div
              @click="updateState(sectionIndex)"
              class="flex cursor-pointer items-center justify-between px-2 py-4"
          >
          <span class="text-lg font-semibold text-brand-800">
            {{ parent.title }}
          </span>
            <div class="relative flex items-center gap-3">
              <div class="cursor-pointer">
                <ChevronRight class="h-5 w-5" v-if="!openStates[sectionIndex]" />
                <ChevronDown class="h-5 w-5" v-else />
              </div>
            </div>
          </div>
          <div class="flex flex-col gap-2" v-if="openStates[sectionIndex]">
            <template v-for="(component, index) in parent.components">
              <div
                  @click="selectComponent(sectionIndex, component, index)"
                  class="flex cursor-pointer items-center justify-between rounded-lg py-1.5 pl-6 pr-2 hover:bg-gray-100"
                  :class="{'bg-gray-200 hover:bg-gray-200': selected?.sectionIndex === sectionIndex && selected?.componentIndex === index}"
              >
                <div class="flex flex-col">
                  <div class="text-xs text-gray-600">Sub-module</div>
                  <div class="text-sm font-medium text-gray-900">
                    {{ component.name }}
                  </div>
                </div>
                <div class="flex items-center justify-between gap-3 px-[10px]">
                  <ChevronRight class="h-5 w-5" />
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <div class="flex h-full flex-1 flex-col mb-20">
        <div class="mb-4 px-6 py-5 rounded-xl bg-gray-50" v-if="!selected">
          <div class="text-lg pb-6 font-semibold text-gray-900 border-b border-gray-200">Settings</div>
          <div class="flex flex-col gap-1 pt-6 text-gray-600">
            <input-wrapper
                field="breadcrumb"
                label-text="Breadcrumb section"
                class="w-full">
              <select id="breadcrumb" v-model="modelValue.breadcrumb" name="url">
                <option
                    :value="b"
                    v-for="(b) in breadcrumbs">
                  {{ b }}
                </option>
              </select>
            </input-wrapper>
            <p>This sets the section name shown in the breadcrumb (e.g. Home / Who We Are / Page). Leave blank to skip the section.</p>
          </div>
        </div>
        <div class="rounded-xl bg-gray-50 px-6 py-5" v-if="!selected">
          <Instructions />
        </div>
        <component
            class="min-h-[90vh]"
            :is="currentComponent"
            :key="`${selected?.sectionIndex} - ${selected?.componentIndex} ${Math.random().toString(36).substring(2, 10)}`"
            :data="selected"
            :sites="sites"
            :forms="forms"
            @update="save"
        ></component>
      </div>
    </div>
    <slot>
      <div class="flex justify-between space-x-xsSpace pt-xsSpace gap-4 sticky bottom-0 w-full bg-gray-200 py-2 px-6">
        <a @click="close"
           class="w-[200px] py-[9px] bg-white rounded-full border border-gray-300 shadow-xs text-md font-semibold hover:bg-gray-100 text-gray-700 text-center cursor-pointer">
          Cancel
        </a>
        <a @click.prevent="save"
           class="w-full py-[9px] rounded-full shadow-xs text-md font-semibold text-white bg-brand-600 hover:bg-brand-700 border border-brand-600 text-center cursor-pointer"
        >Save changes</a>
      </div>
    </slot>
  </div>
</template>
<script setup>
import { ref, markRaw, computed } from "vue";
import ChevronRight from "@/assets/img/icons/chevron-right.svg";
import ChevronDown from "@/assets/img/icons/chevron-down.svg";
import Instructions from "@/components/builders/Instructions.vue";
import VItems from "@/components/builders/Items.vue";
import VLinks from "@/components/builders/Links.vue";
import VHeader from "@/components/builders/Header.vue";
import VLogos from "@/components/builders/Logos.vue";
import VCollectionCarousel from "@/components/builders/CollectionCarousel.vue";
import VNewsGrid from "@/components/builders/NewsGrid.vue";
import VVideoGrid from "@/components/builders/VideoGrid.vue";
import VParagraph from "@/components/builders/Paragraph.vue";
import VImageBlock from "@/components/builders/ImageBlock.vue";
import InputWrapper from "@/components/common/InputWrapper.vue";
import ContactUs from "@/components/builders/ContactUs.vue";
import HorizontalTabs from "@/components/builders/HorizontalTabs.vue";

const emit = defineEmits(["save", "close"]);
const props = defineProps({
  modelValue: {
    required: true,
    type: Object,
  },
  sites: {
    type: Array,
    default: () => {
      return []
    }
  },
  forms: {
    type: Array,
    default: () => {
      return []
    }
  },
  breadcrumbs: {
    type: Array,
    default: () => {
      return []
    }
  },
});

const openStates = ref(JSON.parse(window.localStorage.getItem("pageBuilderOpenStates")));
const sections = ref(props.modelValue?.sections ?? []);
let selected = ref(null);
const componentMaps = ref({
  sliders: markRaw(VItems),
  vertical_tabs: markRaw(VItems),
  links: markRaw(VLinks),
  header: markRaw(VHeader),
  callout: markRaw(VHeader),
  link_grid: markRaw(VLinks),
  logos: markRaw(VLogos),
  carousel: markRaw(VCollectionCarousel),
  news_grid: markRaw(VNewsGrid),
  video_grid: markRaw(VVideoGrid),
  paragraph: markRaw(VParagraph),
  image_block: markRaw(VImageBlock),
  timeline_items: markRaw(VItems),
  bullet_points: markRaw(VLinks),
  pricing: markRaw(VLinks),
  feature_items: markRaw(VLinks),
  faqs: markRaw(VLinks),
  link_cards: markRaw(VItems),
  contact_us: markRaw(ContactUs),
  horizontal_tabs: markRaw(HorizontalTabs),
  testimonial_slider: markRaw(VItems),
});

if (!openStates.value) {
  openStates.value = {};

  sections.value.forEach((item, index) => {
    openStates.value[index] = true;
  });

  window.localStorage.setItem("pageBuilderOpenStates", JSON.stringify(openStates.value));
}

const updateState = (sectionIndex) => {
  openStates.value[sectionIndex] = !openStates.value[sectionIndex];
  window.localStorage.setItem("pageBuilderOpenStates", JSON.stringify(openStates.value));
};

const selectComponent = (sectionIndex, component, index) => {
  selected.value = {
    page: props.modelValue,
    component: component,
    componentIndex: index,
    sectionIndex: sectionIndex,
  };
};

const close = () => {
  emit("close", props.modelValue);
};

const save = (redirect = true) => {
  emit("save", {page: props.modelValue, redirect: redirect});
};

const currentComponent = computed(() => {
  if (!selected.value?.component?.type) {
    return '';
  }

  return componentMaps.value[selected.value?.component?.type];
});
</script>
