<template>
  <PageLayout title="Search Page" description="Configure and optimize a powerful real estate search page, delivering an enhanced user experience and driving lead generation through seamless property discovery.">
    <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">
        <label>LAYOUT</label>
        <LayoutConfig v-model="pageConfig.layout" />
      </div>
    </div>
    <ListingFilter :site-config="pageConfig" ref="listingRef" />
    <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 {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 LayoutConfig from "@/admin/common/Layout.vue";
import PageLayout from "@/admin/common/PageLayout.vue";
import MetaTags from "@/admin/common/MetaTags.vue";
import PageUrl from '@/admin/common/PageUrl.vue'

const allConditions=ref([])
provide('allConditions', allConditions)

const pageConfig=ref({})
const initialUrl=ref('')
const pageUrlRef=useTemplateRef('page-url')
const listingFilter = useTemplateRef('listingRef');

async function getInitialPageInfo(){
  const url=`/wp-plugin/admin/listing-search/searchCondition/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 {allListingId, pluginPage={}, allListingValues=[], sort}=data
    const defaultConfig={
      pageName: 'Property Search',
      uri: 'listing',  // fixed value
      layout: 'map-grid', // map, map-grid
      metaTagHtml: ''
    }
    pageConfig.value = mergeDefaults(
        {...pluginPage, id: allListingId, sort},
        defaultConfig, {overrideEmpty: true}
    )
    initialUrl.value=pageConfig.value.uri

    // initial listing values
    allConditions.value=allListingValues.map(v=> {
      const orderKeys = Object.keys(v.data)
      if(!('orderKeys' in v)){
        return {...v, orderKeys}
      }
      // normalize initial order keys
      if(v.orderKeys?.length !== orderKeys.length){
        // dirty data
        return {...v, orderKeys};
      }
      return v
    })
  } catch (error) {
    console.error('Error fetching initial page info:', error);
  }
}

const fetching=ref(false)
onBeforeMount(async ()=> {
  fetching.value=true
  try{
    await getInitialPageInfo();
  } catch (error) {
    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')
async function savePageConfig(){
  const { pageName, layout, metaTagHtml,uri } = pageConfig.value
  const response = await http.post(`/wp-plugin/admin/common/page/setting/update`, {
    data: {
      type: 'search',
      pageName,
      metaTag: metaTagsRef.value.getValueString(),
      metaTagHtml,
      layout,
      uri
    }
  });
  if (response?.status?.code !== 0) {
    throw new Error(response?.status?.msg);
  }
  // response.data is bool
  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);
    let {data={}, orderKeys=[]}=rawData
    const dataKeys=Object.keys(data)
    // final check order keys, keep with data
    orderKeys=orderKeys.filter(v=> dataKeys.includes(v))
    return {
      data,
      // uiConfig: {},
      onlyId: uuid(),
      orderKeys,
    }
  }).filter(Boolean);
  const params={
    id: pageConfig.value.id,
    name: 'All Listings',
    sort: listingFilter.value.sortCondition,
    listingType: 1,
    values
  }
  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);
  }
}
async function flushUrlRewrite(){
  await http.get('/update-routes')
}
async function onSave(){
  if(disableSave.value) return
  // auto confirm page-url
  pageUrlRef.value.confirm()
  try {
    saving.value = true
    await Promise.all([savePageConfig(), saveListingFilters()])
    await flushUrlRewrite()
    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 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"], select {
  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>