<template>
  <PageLayout title="Featured Listings"
              description="Create and display a curated selection of featured properties on IDX
              pages, enhancing property visibility and driving engagement to boost
              lead generation.">
    <template #button>
      <button :class="['btn-save', { disable: disableSave }]" @click.prevent="onSave">
        {{ saving ? "Saving.." : "Save" }}
      </button>
    </template>

    <div class="form-groups">
      <div class="form-group">
        <label>PAGE NAME</label>
        <input
            type="text"
            placeholder="Type something..."
            v-model="pageConfig.pageName"
            class="page-name"
            maxlength="100"
            :readonly="readonlyMode"
        />
      </div>

      <div class="form-group">
        <label>PAGE URL</label>
        <PageUrl
            v-model="pageConfig.uri"
            :page-config="pageConfig"
            :initial-val="initialUrl"
            ref="page-url"
        />
      </div>

      <MetaTags class="form-group" ref="metaTags" v-model="pageConfig.metaTagHtml"/>
    </div>
    <ListingFilter :site-config="pageConfig" ref="listingRef" />
    <StyleConfig :config="pageConfig.styleConfig" @update="updateStyleConfig"/>
    <Loading :loading="fetching" />
  </PageLayout>
</template>

<script setup>
import { onBeforeMount, ref, provide, toRaw, useTemplateRef } from "vue";
import http from "@/api";
import ListingFilter from "@/admin/common/ListingFilter.vue";
import PageLayout from "@/admin/common/PageLayout.vue";
import StyleConfig from "./styleConfig.vue";
import { v4 as uuid } from "uuid";
import { mergeDefaults } from "@/admin/utils.js";
import Loading from "@/admin/ui/loading.vue";
import { showToast } from "@/admin/ui/constant.js";
import MetaTags from "@/admin/common/MetaTags.vue";
import PageUrl from '@/admin/common/PageUrl.vue'

const allConditions = ref([]);
provide("allConditions", allConditions);

const pageInfo = ref({});
const pageConfig = ref({});

const initialUrl=ref('')
const pageUrlRef=useTemplateRef('page-url')

async function getInitialPageInfo() {
  const url = `/wp-plugin/admin/featured-listing/init-info`;
  try {
    const response = await http.get(url);
    if (response?.status?.code !== 0) {
      throw new Error(`HTTP error! status: ${response?.status?.msg}`);
    }
    const data = response.data;
    const {
      featureListingId,
      featureListingName,
      pluginPage = {},
      pageConfigMap = {},
      featuredListingValue = [],
      sort
    } = data;
    pageInfo.value = data;
    const defaultConfig = {
      pageName: "Featured Listings Page",
      uri: "feature-listing", // fixed value
      layout: "map-grid", // map, map-grid
      metaTagHtml: "",
    };
    pageConfig.value = mergeDefaults(
        {
          ...pluginPage,
          id: featureListingId,
          name: featureListingName,
          styleConfig: pageConfigMap,
          sort
        },
        defaultConfig,
        { overrideEmpty: true }
    );
    initialUrl.value = pageConfig.value.uri

    // initial listing values
    allConditions.value = featuredListingValue;
  } catch (error) {
    console.error("Error fetching initial page info:", error);
  }
}

const fetching = ref(false);

onBeforeMount(async () => {
  fetching.value = true;
  try {
    await getInitialPageInfo();
  } catch (error) {
    console.error("Error fetching page info:", error.message);
    showToast("Error fetching page info:" + error.message, { err: true });
  } finally {
    fetching.value = false;
  }
});

const saving=ref(false)
const disableSave=computed(()=> {
  return !pageConfig.value?.id || !pageConfig.value?.pageName || saving.value || !pageConfig.value?.uri
})
const readonlyMode=computed(()=>fetching.value || saving.value)
const metaTagsRef = useTemplateRef('metaTags')
const listingFilter = useTemplateRef('listingRef');
async function savePageConfig() {
  const { pageName, metaTagHtml, layout, uri } = pageConfig.value;
  const response = await http.post(
    `/wp-plugin/admin/common/page/setting/update`,
    {
      data: {
        type: "featured_listing",
        pageName,
        metaTag: metaTagsRef.value.getValueString(),
        metaTagHtml,
        layout,
        uri
      },
    }
  );
  if (response?.status?.code !== 0) {
    throw new Error(response?.status?.msg);
  }
  if (response.data) {
    pageConfig.value = { ...pageConfig.value, pageName, metaTagHtml, layout,uri };
    initialUrl.value = uri
  }
}
async function saveListingFilters() {
  const values = allConditions.value
    .map((group) => {
      const rawData = toRaw(group);
      return {
        data: rawData.data || {},
        // uiConfig: {},
        onlyId: uuid(),
      };
    })
    .filter(Boolean);
  const params = {
    id: pageConfig.value.id,
    name: pageConfig.value.name,
    sort: listingFilter.value.sortCondition,
    listingType: 1,
    values,
  };
  // console.log('save page params: ', params)
  const response = await http.post(
    `/wp-plugin/admin/listing-search/searchCondition/saveOrUpdate`,
    {
      data: params,
    }
  );
  if (response?.status?.code !== 0) {
    throw new Error(response?.status?.msg);
  }
}
let styleData = ref({});
function updateStyleConfig(styleConfigData) {
  styleData.value = styleConfigData;
}

async function saveStyleConfig() {
  const response = await http.post(
    `/wp-plugin/admin/common/page/page-config/update/FEATURED_LISTING`,
    {
      data: {
        ...styleData.value,
      },
    }
  );
  if (response?.status?.code !== 0) {
    throw new Error(response?.status?.msg);
  }
  if (response.data) {
    pageConfig.value.styleConfig = response.data?.pageConfigMap || {};
  }
}
async function flushUrlRewrite(){
  await http.get('/update-routes')
}
async function onSave() {
  if (disableSave.value) return;
  pageUrlRef.value.confirm()
  try {
    saving.value = true;
    let ps = [savePageConfig(), saveListingFilters()];
    if (Object.keys(styleData.value).length > 0) {
      ps.push(saveStyleConfig());
    }
    await Promise.all(ps);
    await flushUrlRewrite()
    showToast("Saved Successfully");
  } catch (err) {
    console.error("Error save page:", err);
    showToast("Save failed. Please try again.", { duration: 3000, err: true });
  } finally {
    saving.value = false;
  }
}
</script>

<style lang="scss" scoped>
.form-groups {
  padding: 22px 20px 20px;
}
.form-group {
  display: flex;
  flex-direction: column;
  row-gap: 8px;
  margin-bottom: 20px;
  input {
    width: max-content;
  }

  label {
    width: 100px;
    font-weight: 500;
    font-size: 11px;
    color: $gray-800;
  }
}

input[type="text"] {
  width: 100%;
  height: 40px;
  padding: 5px 12px;
  border: 1px solid $gray-600;
  border-radius: $radius-small;
  font-size: 14px;
  box-shadow: none;
  &:hover,
  &:focus {
    border-color: $color-theme;
  }
}
</style>
