<template>
  <div class="rounded-xl bg-gray-50 px-6 py-5">
    <div class="flex justify-between pb-2">
      <div class="flex justify-between w-full py-1">
        <div class="min-w-[50%] w-full">
          <p class="text-lg font-semibold text-gray-900">
            {{ componentData.name }}
          </p>
          <p class="text-sm text-gray-600 mt-1">
            {{ componentData.supportive_text }}
          </p>
          <input-wrapper
              v-if="componentData.hasOwnProperty('title')"
              is-vertical
              field="title"
              label-text="Title *"
              class="w-[50%] my-8"
              :value="componentData.title"
              :limit="100"
          >
            <input
                v-model="componentData.title"
                name="title"
                type="text"
                placeholder="Title"
                :maxlength="100"
                class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
            />
          </input-wrapper>
        </div>
        <div>
          <a
              @click="addItem"
              class="text-sm cursor-pointer flex items-center justify-center gap-1 rounded-[99px] border border-brand-600 bg-brand-500 px-3.5 py-2 font-semibold text-white hover:bg-brand-600"
              :class="{ 'border-gray-100 bg-gray-100 !text-gray-400 hover:bg-gray-100': componentData.data?.length >= componentData.max_items }"
          >
            <PlusIcon class="h-5 w-5"></PlusIcon>
            <span>Add</span>
          </a>
        </div>
      </div>
    </div>
    <div class="flex flex-col gap-3">
      <div
          v-for="(item, index) in componentData.data"
          class="flex flex-col gap-4 rounded-xl px-6 py-4 bg-gray-200"
          :key="index"
          :ref="index === componentData.data.length - 1 ? (el) => (lastItemRef = el) : null"
      >
        <div class="flex items-center justify-between">
          <div class="text-lg font-semibold text-gray-900">
            Item #{{ index + 1 }}
          </div>
          <div class="relative flex items-end">
            <ActionMenu @removeItem="handleDeleteItem(index)"/>
          </div>
        </div>
        <div class="flex flex-col gap-6">
          <div class="flex gap-4" v-if="!componentData?.hasOwnProperty('has_type_switcher') || componentData?.has_type_switcher">
            <label v-for="option in options" class="flex items-center gap-2 cursor-pointer">
              <input
                  :name="`content_type${index}`"
                  type="radio"
                  :value="option.value"
                  v-model="item.content_type"
                  class="checked:bg-brand-600 hover:bg-brand-600 checked:hover:bg-brand-600 focus:bg-brand-600 focus:ring-brand-600 focus:checked:bg-brand-600 rounded-full"
                  @change="updateType(item)"
              />
              <span>{{ option.label }}</span>
            </label>
          </div>
          <div class="flex flex-col gap-1.5" v-if="!item.hasOwnProperty('content_type') || item.content_type === 'content'">
            <Header v-if="['feature_items', 'faqs', 'pricing'].includes(componentData.type)" :data="item"></Header>
            <input-wrapper
                v-else
                is-vertical
                field="title"
                label-text="Title *"
                class="w-full mb-4"
                :value="item.title"
                :limit="componentData?.max_title ?? 200"
            >
              <input
                  v-if="!isBulletPoint"
                  v-model="item.title"
                  name="title"
                  type="text"
                  placeholder="Title"
                  :maxlength="componentData?.max_title ?? 200"
                  class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
              />
              <textarea
                  v-if="isBulletPoint"
                  v-model="item.title"
                  name="title"
                  placeholder="Title"
                  :maxlength="componentData?.max_title ?? 200"
                  rows="4"
                  class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
              />
            </input-wrapper>
            <linked-to
                v-if="item.hasOwnProperty('type')"
                label="Linked to"
                :name="`link_${index + 1}`"
                v-model:type="item.type"
                v-model:url="item.url"
                v-model:openInNewTab="item.open_in_new_tab"
                :sites="sites"
            />
          </div>
          <div v-else>
            <input-wrapper
                is-vertical
                field="image"
                label-text="Image *"
                class="w-full mb-4"
                :value="item.image"
            >
              <VFileUpload v-model="item.image" />
            </input-wrapper>
          </div>
        </div>
      </div>
    </div>
  </div>
  <VModal ref="modalRef" entity="link" :callback="deleteCallback"></VModal>
</template>
<script setup>
import {ref, nextTick, computed, inject} from "vue";
import PlusIcon from "@/assets/img/icons/plus.svg";
import {defaultProps} from "@/components/helpers/defaultProps";
import {createLink} from "@/components/helpers/pageBuilderFactory";
import ActionMenu from "@/components/common/ActionMenu.vue";
import InputWrapper from "@/components/common/InputWrapper.vue";
import DefaultFileUpload from "@/components/common/FileUpload.vue";
import LinkedTo from "@/components/common/LinkedTo.vue";
import Header from "@/components/builders/Header.vue";
import VModal from "@/components/common/Modal.vue";

// Inject the FileUpload component or fallback to the default one
const VFileUpload = inject("VFileUpload", DefaultFileUpload);

const emit = defineEmits(["update"]);
const props = defineProps({
  ...defaultProps,
});

const options = [{value: 'content', label: 'Content'}, {value: 'image_only', label: 'Image Only'}];

const componentData = ref(props.data.component);
const modalRef = ref(null);
const lastItemRef = ref(null);
const deleteItemIndex = ref(null);

const isBulletPoint = computed(() => {
  return componentData.value.type === 'bullet_points';
});

const isFeatureItem = computed(() => {
  return componentData.value.type === 'feature_items';
});

function addItem() {
  if (!componentData.value.hasOwnProperty('data')) {
    componentData.value.data = [];
  }

  if (componentData.value.data?.length >= componentData.value.max_items) {
    return;
  }
  componentData.value.data?.push(createLink({}, componentData.value.type));

  nextTick(() => {
    if (lastItemRef.value) {
      lastItemRef.value.scrollIntoView({behavior: "smooth"});
    }
  });

  emit("update", false);
}

const handleDeleteItem = (index) => {
  deleteItemIndex.value = index;
  modalRef?.value?.open(index);
}

const deleteCallback = (index) => {
  componentData.value.data?.splice(index, 1);
  emit("update", false);
};

const updateType = (item) => {
  if (item.content_type === 'content') {
    delete item['image'];
    item.icon = null;
    item.title = null;
    item.supporting_text = null;
  } else {
    item.image = null;
    delete item['icon'];
    delete item['supporting_text'];
    delete item['title'];
  }
};
</script>
