<template>
  <PageLayout title="Market Report" description="Generate and configure the shortcode of Market Report, then create a new WordPress Page and insert the shortcode into it, improving market transparency and attracting investor attention to fuel business opportunities.">
    <template #button>
      <button :class="['btn-save','btn-add-report', {'disable': disableSave}]" @click.prevent="addReport">Add To Report List</button>
      <span v-if="copied">Copied!</span>
      <button v-else class="btn-save" @click.prevent="onCopy">
        Copy to clipboard
      </button>
    </template>
    <MetaTags class="market-form-groups" ref="metaTags" v-model="metaTagHtml" type="marketReport" isShortCode/>
    <ListingFilter class="market-report-short-code" :maxGroupNumber="1" :config="listingConfig" @ready="dateFields=$event"/>
    <ReportConfig @update="updateConfig" />
  </PageLayout>
</template>

<script setup>
import { ref, provide, toRaw, useTemplateRef } from "vue";
import ListingFilter from "@/admin/common/ListingFilter.vue";
import ReportConfig from "./report-config.vue";
import { useCopy } from "@/hooks/useCopy.js";
import MetaTags from "@/admin/common/MetaTags.vue";
import PageLayout from "@/admin/common/PageLayout.vue";
import {formatShortConditions, saveShortCodeLog, types} from "@/admin/shortcodes/common.js";
import { showToast } from "@/admin/ui/constant.js";
import http from "@/api/index.js";

const listingConfig = {
  title: "Market Criteria",
  tip: "Define the criteria used to generate the market report",
  criteriaUrl: "/wp-plugin/market-report/conditions",
  listingCountUrl: "/wp-plugin/market-report/match-count",
  isMarketReport: true,
};

const allConditions = ref([
  { data: { location: {} }, orderKeys: ["location"]},
]);
provide("allConditions", allConditions);

const { copied, copyCode } = useCopy();
let currentConfigData = ref({});
function updateConfig({ configData }) {
  currentConfigData.value = configData;
}
const metaTagHtml = ref('')
const metaTagsRef = useTemplateRef('metaTags')
let dateFields = []
function onCopy() {
  const values = allConditions.value.map((group) => {
      return { data: toRaw(group.data || {}) };
    }).filter(Boolean);
  let location = []
  if(values[0]?.data.location) {
    Object.values(values[0]?.data.location).forEach(list => {
      location = location.concat(list);
    })
  }
  const { title, show_new, show_pending, show_sold } = currentConfigData.value;
  const data = {
    title,
    location: location.join(','),
    show_new,
    show_pending,
    show_sold,
    meta: metaTagsRef.value.getValueString(),
    conditions: formatShortConditions(allConditions.value, dateFields),
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
  }
  const shortcode = `[lofty_idx_market_report][[${JSON.stringify(data, null, 2)}]][/lofty_idx_market_report]`;
  copyCode(shortcode);
  saveShortCodeLog(types.MarketReport, shortcode);
}

const disableSave = ref(false)
async function addReport() {
  if(disableSave.value) {
    return
  }
  const { title, show_new, show_pending, show_sold } = currentConfigData.value;
  if(!title) {
    showToast("Please fill the report title.", { duration: 3000, err: true });
    return
  }
  if(!/^[a-zA-Z0-9_\- ]*$/.test(title)) {
    showToast("Special characters are not allowed in the title.", { duration: 3000, err: true });
    return
  }
  disableSave.value = true
  const values = allConditions.value.map((group) => {
    return { data: toRaw(group.data || {}) };
  }).filter(Boolean);
  const res = await http.post('/admin/listing-search/short-code/saveOrUpdate', {
    data: {
      values
    }
  })
  const data = {
    title,
    filterName: res.data,
    extraInfoMap: {
      displayNewListing: show_new,
      displayPendingListings: show_pending,
      displaySoldListings: show_sold
    }
  }
  const response = await http.post('/admin/report/save', { data })
  if(response.status.code === 0) {
    showToast('Add Successfully');
    setTimeout(()=>{
      const params = new URLSearchParams(window.location.search);
      params.set('page', 'lofty-idx-pages');
      params.set('sub', 'market-report-collection');
      window.location.search = params.toString();
    }, 1000)
  } else {
    let msg = 'A report with the same filters already exists. Please do not create a duplicate'
    if(response.status.code === 230001) {
      msg = 'This report title is already in use. Please choose a different one'
    }
    showToast(msg, { duration: 5000, err: true });
    disableSave.value = false
  }
}

</script>
<style lang="scss">
.btn-add-report {
  margin-left: auto;
  margin-right: 10px;
}
.market-form-groups {
  padding: 22px 20px 20px;
  .meta-tag-content {
    margin-top: 8px;
  }
}
.market-report-short-code {
  padding-bottom: 0!important;
  .group {
    border-bottom: none !important;
    .header {
      .title {
        h3 {
          display: none !important;
        }
        .description {
          display: none !important;
        }
      }
    }
  }
  button.add-group-btn.disable {
    display: none !important;
  }
}
</style>
