<template>
  <div class="flex flex-col gap-5">
    <div>
      <p v-if="label" class="text-sm text-gray-700 font-medium py-2">{{ label }}</p>
      <div class="text-sm flex items-center gap-6 font-medium text-gray-700">
        <label v-for="option in options" class="flex items-center gap-2 cursor-pointer">
          <input
              :name="name"
              type="radio"
              :value="option"
              v-model="type"
              @click="() => url = null"
              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"
          />
          <span>{{ toReadableWords(option) }}</span>
        </label>
      </div>
    </div>
    <div class="flex flex-col gap-2">
      <component :is="getComponentByType(type)" v-model="url" v-model:url="url" :type="type" :sites="sites" :items="forms"/>
      <input type="hidden" name="url" :value="url" />
    </div>
    <div class="flex items-center gap-2">
      <VToggle class="mb-1" name="open_in_new_tab" v-model="openInNewTab"  title="Open in a new tab" />
    </div>
  </div>
</template>

<script setup>
import {inject} from "vue";
import VToggle from "@/components/common/Toggle.vue";
import SiteContent from "@/components/common/SiteContent.vue";
import ExternalPage from "@/components/common/ExternalPage.vue";
import DefaultFileUpload from "@/components/common/FileUpload.vue";
import ItemSelect from "@/components/common/ItemSelect.vue";

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

const type = defineModel("type", { default: "site-content" });
const url = defineModel("url");
const openInNewTab = defineModel("openInNewTab");

const props = defineProps({
  label: { type: String, required: false },
  sites: { type: Array, required: false, default: () => []},
  forms: { type: Array, required: false, default: () => []},
  name: { type: String, required: true },
  options: { type: Array, required: false, default: ["site-content", "external-page", 'download', 'form'] },
});

const toReadableWords = (input) => {
  return input
      .split('-') // Split the string by hyphens
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' '); // Join the words with spaces
}

// Map the type to the corresponding component
const getComponentByType = (type) => {
  const components = {
    "site-content": SiteContent,
    "external-page": ExternalPage,
    "download": VFileUpload,
    "form": ItemSelect,
  };
  return components[type] || null;
};
</script>
