<template>
  <div class="item-edit">
    <div class="flex items-start gap-4 px-6 pt-4 h-full min-h-[90vh]">
      <div class="flex flex-1 flex-col gap-4 mb-4">
        <div v-if="hasLines">
          <div class="flex justify-between mb-4">
            <div class="flex flex-col gap-1">
              <p class="text-base font-semibold text-gray-900">Events</p>
              <p class="text-sm">
                This timeline item can contain up to {{ item?.max_items }} events.
              </p>
            </div>
            <button
                :disabled="advancedForm.lines.length >=  item?.max_items"
                @click="addLine"
                class="text-sm cursor-pointer flex items-center justify-center gap-1 rounded-[99px] border border-brand-600 bg-brand-500 px-3.5 h-[40px] font-semibold text-white hover:bg-brand-600"
                :class="{ 'border-gray-100 bg-gray-100 !text-gray-400 hover:bg-gray-100': advancedForm.lines.length >= item?.max_items }"
            >
              <PlusIcon class="h-5 w-5"></PlusIcon>
              <span>Event</span>
            </button>
          </div>
          <div class="flex flex-col gap-4">
            <div
                v-for="(line, index) in advancedForm.lines"
                :key="index"
                class="flex flex-col gap-2 rounded-lg px-6 pt-4 pb-[40px] bg-gray-50"
            >
              <div class="flex justify-between items-center border-b border-gray-200 pb-3 mb-4">
                <p class="text-lg font-semibold text-gray-900"> Event #{{ index + 1 }}</p>
                <ActionMenu @removeItem="handleDeleteItem(index)"/>
              </div>
              <input-wrapper
                  is-vertical
                  field="line.title"
                  label-text="Heading *"
                  class="w-full"
                  :value="line.title"
              >
                <input
                    v-model="line.title"
                    name="line.title"
                    type="text"
                    placeholder="Heading"
                    class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
                />
              </input-wrapper>
              <input-wrapper
                  is-vertical
                  field="line.description"
                  label-text="Description *"
                  class="w-full"
                  :value="descriptionWordCount(line.description)"
                  :show-count="true"
              >
                <QuillEditor v-model="line.description"/>
              </input-wrapper>
            </div>
          </div>
        </div>

        <card title="Description" v-else>
          <div class="flex flex-col gap-8">
            <input-wrapper
                is-vertical
                field="title"
                label-text="Title *"
                class="w-full"
                :value="basicForm.title"
                :limit="51"
            >
              <input
                  v-model="basicForm.title"
                  name="title"
                  type="text"
                  placeholder="Title"
                  :maxlength="51"
                  class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
              />
            </input-wrapper>
            <input-wrapper
                is-vertical
                field="description"
                label-text="Description *"
                class="w-full mb-4"
                :value="descriptionWordCount(basicForm.description)"
                :show-count="true"
            >
              <QuillEditor v-model="basicForm.description" :limit="basicForm.limit ?? 1000"/>
            </input-wrapper>
          </div>
        </card>
        <VButton v-if="basicForm.hasOwnProperty('primary_button')" :button="basicForm.primary_button" :sites="sites" :forms="forms"/>
        <VButton v-if="basicForm.hasOwnProperty('secondary_button')" :button="basicForm.secondary_button" :sites="sites" :forms="forms"/>
      </div>
      <div class="flex w-full max-w-[356px] flex-col gap-4">
        <template v-if="!hasLines">
          <card title="Visibility" supporting_text="Toggle off if you'd like to hide this item">
            <VToggle v-model="basicForm.public" name="public" label="Public"/>
          </card>
          <card title="Featured Image" supporting_text="Recommended dimension: 1200*1060px">
            <VFileUpload
                name="image"
                height="h-[200px]"
                v-model="basicForm.featured_image"
            />
          </card>
        </template>
        <template v-else>
          <card title="Timeline item title" supporting_text="To indicate the time period of the events">
            <input-wrapper
                is-vertical
                field="title"
                label-text="Timeline item title *"
                class="w-full"
                :value="advancedForm.title"
                :limit="20"
            >
              <input
                  v-model="advancedForm.title"
                  name="title"
                  type="text"
                  placeholder="Title"
                  :maxlength="20"
                  class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
              />
            </input-wrapper>
          </card>
          <card title="Event group title" supporting_text="The title for the group of events under this time period">
            <input-wrapper
                is-vertical
                field="title"
                label-text="Event group title *"
                class="w-full"
                :value="advancedForm.group_title"
                :limit="51"
            >
              <input
                  v-model="advancedForm.group_title"
                  name="title"
                  type="text"
                  placeholder="Title"
                  :maxlength="51"
                  class="border-1 border-solid border-gray-300 rounded-lg bg-white w-full"
              />
            </input-wrapper>
          </card>
        </template>
      </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>
    <VModal ref="modalRef" :entity="'event'" :callback="removeLine"></VModal>
  </div>
</template>

<script setup>
import {ref, computed, inject} from "vue";
import QuillEditor from "@/components/common/QuillEditor.vue";
import Card from "@/components/common/Card.vue";
import InputWrapper from "@/components/common/InputWrapper.vue";
import VToggle from "@/components/common/Toggle.vue";
import DefaultFileUpload from "@/components/common/FileUpload.vue";

// Inject the FileUpload component or fallback to the default one
const VFileUpload = inject("VFileUpload", DefaultFileUpload);
import axios from "axios";
import VButton from "@/components/common/Button.vue";
import PlusIcon from "@/assets/img/icons/plus.svg";
import ActionMenu from "@/components/common/ActionMenu.vue";
import VModal from "@/components/common/Modal.vue";

const emit = defineEmits(["update"]);

const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
  saveEndpoint: {
    type: String,
    required: false,
  },
  cancelEndpoint: {
    type: String,
    required: false,
  },
  sites: {
    type: Array,
    required: true,
  },
  forms: {
    type: Array,
    required: true,
  },
});

const hasLines = computed(() => {
  return props.item.hasOwnProperty('lines');
});

const modalRef = ref(null);

const basicForm = ref({
  public: props.item.public,
  title: props.item.title,
  description: props.item.description,
  limit: props.item?.limit ?? 1000,
  featured_image: props.item.featured_image,
});

const advancedForm = ref({
  title: props.item.title,
  title_group: props.item?.title_group,
  max_items: props.item?.max_items,
  lines: props.item.lines || [],
});

if (props.item.hasOwnProperty('primary_button')) {
  basicForm.value.primary_button = props.item.primary_button;
}

if (props.item.hasOwnProperty('secondary_button')) {
  basicForm.value.secondary_button = props.item.secondary_button;
}

const addLine = () => {
  advancedForm.value.lines.push({title: "", description: ""});
};

const save = () => {
  let form = hasLines.value ? advancedForm : basicForm;

  if (props.saveEndpoint) {
    axios.post(props.saveEndpoint, form.value).then((data) => {
      emit("update", data);
      if (props.cancelEndpoint) {
        // window.location.href = props.cancelEndpoint;
      }
    });

    return;
  }

  emit("update", form.value);
};

const removeLine = (index) => {
  advancedForm.value.lines.splice(index, 1);
  save();
};

const close = () => {
  let form = hasLines.value ? advancedForm : basicForm;
  emit("close", form.value);

  if (props.cancelEndpoint) {
    window.location.href = props.cancelEndpoint;
  }
};

const descriptionWordCount = (description) => {
  const plainText = description?.replace(/<[^>]*>/g, ' ')?.trim();
  const words = plainText?.split(/\s+/)?.filter(word => word?.length > 0);
  return words?.length || 0;
};

const handleDeleteItem = (index) => {
  modalRef?.value?.open(index);
};
</script>