<template>
  <PageLayout title="Listing Detail" description="The Listing Detail page is included by default and does not require configuration of the page content. To preview the page, you can click on any listing
        and view it through the Search Page or other IDX pages. However, you can set the Meta tags below to optimize SEO.">
    <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 URL</label>
        <input type="text" :value="pageUrl" readonly class="suffix">
      </div>

      <MetaTags class="form-group"
                ref="metaTags"
                type="listingDetail"
                v-model="config.metaTagHtml"/>
      <Loading :loading="loading"/>
    </div>
  </PageLayout>
</template>

<script setup>
import PageLayout from "@/admin/common/PageLayout.vue";
import MetaTags from "@/admin/common/MetaTags.vue";
import http from "@/api/index.js";
import Loading from "@/admin/ui/loading.vue";
import { showToast } from "@/admin/ui/constant.js";

const config = reactive({
  domain: '',
  uri: '',
  metaTagHtml: '',
})
const saving = ref(false)
const loading = ref(false)
const disableSave = computed(()=> saving.value || loading.value)
const pageUrl = computed(()=>`https://${config.domain}/${config.uri}`)
getPageInfo();
async function getPageInfo() {
  loading.value = true
  const res = await http.get('/wp-plugin/admin/listing-detail/active-init-info');
  const pluginPage = res.data.pluginPage
  config.domain = pluginPage.domain
  config.metaTagHtml = pluginPage.metaTagHtml || ''
  config.uri = pluginPage.uri
  loading.value = false
}
const metaTagsRef = useTemplateRef('metaTags')
async function onSave() {
  if(disableSave.value) {
    return
  }
  try {
    saving.value = true
    await http.post(`/wp-plugin/admin/common/page/setting/update`, {
      data: {
        type: 'listing_detail',
        metaTag: metaTagsRef.value.getValueString(),
        metaTagHtml: config.metaTagHtml
      }
    });
    showToast('Saved Successfully')
  } catch (err){
    console.error('Error save page:', err);
    showToast('Error save page:' + err.message, {err: true})
  } finally {
    saving.value = false
  }
}
</script>
<style scoped lang="scss">
.form-groups {
  padding: 22px 20px 20px;
}
.form-group {
  display: flex;
  flex-direction: column;
  row-gap: 8px;
  margin-bottom: 20px;

  label {
    width: 100px;
    font-weight: 500;
    font-size: 11px;
    color: $gray-800;
  }
  .domain {
    color: $gray-700;
    font-size: 14px;
    white-space: nowrap;
  }
}
</style>