<template>
  <PageLayout title="Market Report Collection" description="Create multiple Market Reports to be displayed centrally on the website, allowing visitors to easily switch between and view different reports.">
    <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" :readonly="readonlyMode"/>
      <div class="form-group">
        <ReportList :pageConfig="pageConfig"/>
      </div>
      <div class="form-group">
        <JsSetting v-model="submitJs" desc="The following code will be executed after successfully clicking the 'Subscribe to the report' button."/>
      </div>
    </div>
    <Loading :loading="fetching" />
  </PageLayout>
</template>

<script setup>
import PageLayout from "@/admin/common/PageLayout.vue";
import { onBeforeMount, ref, useTemplateRef } from "vue";
import PageUrl from "@/admin/common/PageUrl.vue";
import ReportList from './reportList.vue';
import { showToast } from "@/admin/ui/constant.js";
import http from "@/api/index.js";
import Loading from "@/admin/ui/loading.vue";
import MetaTags from "@/admin/common/MetaTags.vue";
import JsSetting from "@/admin/common/SubmitJs.vue";

const pageConfig = ref({})
const initialUrl = ref('')
const pageUrlRef = useTemplateRef('page-url')
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 submitJs = ref("");
async function getMarketPageInfo() {
  const url = `/wp-plugin/admin/report/init-info`;
  try {
    const res = await http.get(url);
    if (res.status.code !== 0) {
      throw new Error(`HTTP error! status: ${response?.status?.msg}`);
    }
    pageConfig.value = res.data.pluginPage;
    initialUrl.value = res.data.pluginPage.uri;
    submitJs.value = res.data.pageConfigMap.submitJs || ''
  } catch (error) {
    console.error("Error fetching initial page info:", error);
  }
}
async function onSave() {
  if (disableSave.value) return;
  pageUrlRef.value.confirm();
  try {
    saving.value = true;
    const res = await http.post(
        `/wp-plugin/admin/common/page/setting/update`,
        {
          data: {
            type: "market_report_page",
            pageName: pageConfig.value.pageName,
            metaTag: metaTagsRef.value.getValueString(),
            metaTagHtml: pageConfig.value.metaTagHtml,
            uri: pageConfig.value.uri
          },
        }
    );
    if (res.status.code === 0) {
      await http.get('/update-routes')
      await saveSubmitJs()
      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;
  }
}

async function saveSubmitJs() {
  await http.post('/wp-plugin/admin/common/page/page-config/update/MARKET_REPORT_PAGE', {
    data: {
      submitJs: submitJs.value
    }
  })
}
const fetching = ref(false)
onBeforeMount(async ()=> {
  fetching.value=true
  try{
    await getMarketPageInfo();
  } catch (error) {
    showToast('Error fetching page info:' + error.message, {err: true})
  }finally {
    fetching.value=false
  }
});
</script>