<script setup>
import DynamicTemplateForm from "@/components/DynamicTemplateForm.vue";
import { useTemplateSchema } from "@/composables/useTemplateSchema";
import { useAuthStore } from "@/stores/authStore";
import { usePagesStore } from "@/stores/pagesStore";
import { useSettingStore } from "@/stores/settingStore";
import { storeToRefs } from "pinia";
import { useField, useForm } from "vee-validate";
import { computed, onMounted, ref, watch } from "vue";
import OverlayLoader from "@/components/OverlayLoader.vue";
import { useRouter } from "vue-router";
import * as yup from "yup";
import { languages } from "@/utils/languageCode";

const authStore = useAuthStore();
const { user: authUser } = storeToRefs(authStore);

const pagesStore = usePagesStore();
const { templates, error, loading } = storeToRefs(pagesStore);
const { fetchTemplates, addPage } = pagesStore;

// Add settings store
const settingStore = useSettingStore();
const { setting } = storeToRefs(settingStore);
const { getSetting } = settingStore;

const router = useRouter();

// Template schema composable
const { generateContentStructure } = useTemplateSchema();

// ─── Check if user is super admin ───────────────────────────────────────────
const isSuperAdmin = computed(() => {
  const u = authUser.value;
  return u?.data?.role === "super_admin" || u?.role === "super_admin";
});

const normalizeLangCode = (raw) => {
  const x = (raw ?? "").toString().trim().toLowerCase();
  if (!x) return "";
  return x === "english" ? "en" : x;
};

/** Same preference order as page editor: franchise profile language, then site language setting. */
const franchisePrimaryLanguageCode = computed(() => {
  const fromFranchise = normalizeLangCode(
    authUser.value?.data?.franchisee?.language,
  );
  const gs = setting.value?.general_settings;
  const row = Array.isArray(gs) ? gs[0] : gs;
  const configured = normalizeLangCode(row?.language_code);
  if (fromFranchise && fromFranchise !== "en") return fromFranchise;
  if (configured && configured !== "en") return configured;
  return fromFranchise || configured || "en";
});

// ─── Language tabs: franchise sees only their preferred language (not English + preferred) ─
const activeLanguage = ref("en");

const languageTabs = computed(() => {
  if (isSuperAdmin.value) return [];

  const pref = franchisePrimaryLanguageCode.value;
  const gs = setting.value?.general_settings;
  const row = Array.isArray(gs) ? gs[0] : gs;
  const nameFromSetting = row?.language_name || "";

  if (pref === "en") {
    return [{ title: "English", tab: "en" }];
  }

  const match = languages.find((l) => l.code === pref);
  return [
    {
      title: nameFromSetting || match?.name || pref.toUpperCase(),
      tab: pref,
    },
  ];
});

watch(
  languageTabs,
  (tabs) => {
    if (!tabs?.length) return;
    const codes = tabs.map((t) => t.tab);
    if (!codes.includes(activeLanguage.value)) {
      activeLanguage.value = codes[0];
    }
  },
  { immediate: true },
);

// ─── Validation Schema ──────────────────────────────────────────────────────
const validationSchema = yup.object({
  pageTitle: yup.string().required("Page title is required"),
});

// ─── Vee-Validate Setup ─────────────────────────────────────────────────────
const { handleSubmit } = useForm({ validationSchema });
const { value: pageTitle, errorMessage: pageTitleError } =
  useField("pageTitle");

onMounted(async () => {
  // Fetch both templates and settings
  await Promise.all([fetchTemplates(), getSetting()]);
});

// ─── Page fields and metadata ───────────────────────────────────────────────
const visibility = ref("publish");
const metaTitle = ref("");
const metaDescription = ref("");
const templatePage = ref(null);

// This will hold the content for the selected template
const contenSec = ref({});

// Watch for changes in templatePage - now uses schema
watch(templatePage, (newVal) => {
  if (newVal) {
    contenSec.value = generateContentStructure(newVal);
  } else {
    contenSec.value = {};
  }
});

// ─── Toggle visibility status between 'publish' and 'draft' ───────────────
const editVisibility = () => {
  visibility.value = visibility.value === "publish" ? "draft" : "publish";
};

// ─── Submit handler with role-based status logic ────────────────────────────────
// In your pages/add.vue - Update the submitPage function
const submitPage = async (isDraft = false) => {
  const formData = new FormData();
  const isSuper = authUser.value?.data?.role === "super_admin";
  const franchiseeId = !isSuper ? authUser.value?.data?.franchisee_id : "";

  // Status logic
  let status;
  status = isDraft ? "draft" : "publish";

  // Language code logic
  const languageCode = isSuper ? "en" : activeLanguage.value;

  // Add normal fields
  formData.append("title", pageTitle.value);
  formData.append("status", status);
  formData.append("template_page", templatePage.value);
  formData.append("seo_title", metaTitle.value);
  formData.append("seo_description", metaDescription.value);
  formData.append("is_global", isSuper ? "1" : "0");
  formData.append("franchisee_id", franchiseeId);
  formData.append("language_code", languageCode);

  // Append content fields
  Object.keys(contenSec.value).forEach((sectionKey) => {
    Object.keys(contenSec.value[sectionKey]).forEach((fieldKey) => {
      // Skip preview and metadata fields
      if (
        [
          "desktopPreview",
          "mobilePreview",
          "bgimagePreview",
          "desktopImageFileName",
          "mobileImageFileName",
          "bgimageFileName",
          "desktopImageId",
          "mobileImageId",
          "bgimageId",
        ].includes(fieldKey)
      ) {
        return;
      }

      const value = contenSec.value[sectionKey][fieldKey];

      if (value instanceof File) {
        // Send as file (direct upload)
        formData.append(`content[${sectionKey}][${fieldKey}]`, value);
      } else if (Array.isArray(value)) {
        // Handle arrays (repeater items, multiple images) as JSON
        formData.append(
          `content[${sectionKey}][${fieldKey}]`,
          JSON.stringify(value),
        );
      } else if (value && typeof value === "string") {
        // Send as URL (from media library)
        formData.append(`content[${sectionKey}][${fieldKey}]`, value);
      } else {
        // Send empty value
        formData.append(`content[${sectionKey}][${fieldKey}]`, "");
      }
    });
  });

  try {
    const response = await addPage(formData);
    if (response.status === true) {
      // Toast is now handled by the store
      router.replace("/pages/list");
    }
  } catch (error) {
    // Error toast is now handled by the store
    // Optional: Additional error handling if needed
  }
};

// ─── Submit handlers ────────────────────────────────────────────────────────
const onSave = handleSubmit(() => submitPage(false));
const onSaveAsDraft = handleSubmit(() => submitPage(true));
</script>

<template>
  <!-- Global overlay loader for saving -->
  <OverlayLoader :loading="loading" />
  <VForm @submit="onSave">
    <div class="d-flex justify-end mb-4">
      <VBtn
        variant="text"
        color="primary"
        prepend-icon="bx-arrow-back"
        @click="router.push('/pages/list')"
      >
        Back
      </VBtn>
    </div>
    <VRow>
      <!-- ========== Main Content Area ========== -->
      <VCol cols="12" md="8">
        <VCard title="Add New Page" class="mb-4">
          <VCardText>
            <!-- Page Title Input -->
            <VTextField
              v-model="pageTitle"
              label="Page Title *"
              placeholder="Add Title"
              outlined
              density="comfortable"
              class="mb-4"
              :error-messages="pageTitleError"
              required
            />
          </VCardText>
        </VCard>

        <!-- ========== Language Tabs (Show for non-super admin) ========== -->
        <VCard v-if="!isSuperAdmin && languageTabs.length > 0" class="mb-4">
          <VCardText>
            <VTabs
              v-model="activeLanguage"
              show-arrows
              class="v-tabs-pill"
              color="primary"
              bg-color="grey-lighten-4"
            >
              <VTab
                v-for="item in languageTabs"
                :key="item.tab"
                :value="item.tab"
                class="text-none font-weight-medium"
                style="min-height: 42px; border-radius: 8px; margin: 0 4px"
              >
                {{ item.title }}
              </VTab>
            </VTabs>
          </VCardText>
        </VCard>

        <!-- Dynamic Template Form -->
        <DynamicTemplateForm
          v-if="templatePage"
          v-model="contenSec"
          :template-slug="templatePage"
          :is-english="activeLanguage === 'en'"
          :user-role="isSuperAdmin ? 'super_admin' : 'franchisee'"
        />

        <!-- ========== SEO Meta Section ========== -->
        <VCard title="SEO Meta Tags">
          <VCardText>
            <!-- Meta Title -->
            <VTextField
              v-model="metaTitle"
              label="Meta Title"
              placeholder="Meta Title"
              outlined
              density="comfortable"
              class="mb-4"
            />

            <!-- Meta Description -->
            <VTextarea
              v-model="metaDescription"
              label="Meta Description"
              rows="5"
              auto-grow
              variant="outlined"
            />
          </VCardText>
        </VCard>
      </VCol>

      <!-- ========== Sidebar Panel ========== -->
      <VCol cols="12" sm="4">
        <VRow style="position: sticky; top: 90px; height: fit-content">
          <!-- Page Attributes -->
          <VCol cols="12">
            <VCard title="Page Attributes">
              <VCardText>
                <VSelect
                  v-model="templatePage"
                  :items="templates"
                  item-title="name"
                  item-value="slug"
                  label="Select page template"
                  outlined
                  density="comfortable"
                />
              </VCardText>
            </VCard>
          </VCol>

          <!-- Publish Actions -->
          <VCol cols="12">
            <VCard title="Publish">
              <VCardText>
                <div class="flex justify-center items-center gap-8">
                  <!-- Save Button -->
                  <VBtn
                    type="submit"
                    color="primary"
                    size="default"
                    class="text-white w-28 flex-shrink-0"
                    :disabled="loading"
                    style="width: 50%"
                  >
                    Save
                  </VBtn>

                  <!-- Save as Draft Button -->
                  <VBtn
                    color="secondary"
                    size="default"
                    class="w-32 flex-shrink-0"
                    :disabled="loading"
                    @click="onSaveAsDraft"
                  >
                    Save as Draft
                  </VBtn>
                </div>
              </VCardText>
            </VCard>
          </VCol>
        </VRow>
      </VCol>
    </VRow>
  </VForm>
</template>

<style scoped>
.v-tabs-pill .v-tab {
  background-color: rgba(var(--v-theme-on-surface), 0.05);
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  transition: all 0.2s ease;
  cursor: pointer;
}

.v-tabs-pill .v-tab:hover {
  background-color: rgba(var(--v-theme-primary), 0.1);
  border-color: rgb(var(--v-theme-primary));
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.v-tabs-pill .v-tab--selected {
  background-color: rgb(var(--v-theme-primary));
  color: white;
  border-color: rgb(var(--v-theme-primary));
  box-shadow: 0 2px 8px rgba(var(--v-theme-primary), 0.3);
}

.btn-fixed-width {
  min-width: 120px;
}
</style>
