<script lang="ts" setup>
import { vue } from '@factor/api'
import { InputOption } from '@factor/ui'
import ElInput from '@factor/ui/ElInput.vue'
import ElForm from '@factor/ui/ElForm.vue'
import type { Site } from '../site'
import type { EditorTool } from './tools'
import ElTool from './ElTool.vue'
import ToolForm from './ToolForm.vue'

const props = defineProps({
  site: {
    type: Object as vue.PropType<Site>,
    required: true,
  },
  tool: {
    type: Object as vue.PropType<EditorTool>,
    required: true,
  },
  saveText: {
    type: String,
    default: 'Save',
  },
})
const control = props.site.settings.factorSites
const loading = vue.ref(false)

const options = [
  new InputOption({
    key: 'editor.hidePageSetup',
    label: 'Page Setup',
    input: 'group',
    options: [
      new InputOption({
        key: 'title',
        label: 'Name',
        input: 'InputText',
        placeholder: 'Page Name',
        isRequired: true,
      }),
      new InputOption({
        key: 'slug',
        label: 'Slug',
        input: 'InputText',
        placeholder: 'my-page',
        isRequired: true,
      }),
    ],
  }),
  new InputOption({
    key: 'editor.hidePageSeo',
    label: 'SEO / Meta Tags',
    input: 'group',
    options: [
      new InputOption({
        key: 'userConfig.seoTitle',
        label: 'Title',
        input: 'InputText',
      }),
      new InputOption({
        key: 'userConfig.seoDescription',
        label: 'Description',
        input: 'InputTextarea',
        props: {
          rows: 5,
        },
      }),
    ],
  }),

]

async function save() {
  loading.value = true
  await props.site.requestManageRegion({
    _action: 'upsert',
    regionCard: props.site.editPageConfig.value,
    delay: 400,
    successMessage: 'Page Saved',
  })
  loading.value = false

  props.site.editPageConfig.value = {}

  control.useTool({ toolId: 'pages' })
}
</script>

<template>
  <ElTool
    :actions="[]"
    v-bind="props"
    :back="{
      name: 'Pages',
      onClick: () => {
        control.useTool({ toolId: 'pages' })
      },
    }"
  >
    <ElForm @submit="save()">
      <ToolForm
        v-model="site.editPageConfig.value"
        :options="options"
      />

      <div class="text-right px-4 py-2">
        <ElInput input="InputSubmit" :loading="loading">
          {{ saveText }}
        </ElInput>
      </div>
    </ElForm>
  </ElTool>
</template>

<style lang="less" scoped>
.region-setting-input {
  --input-bg: theme('colors.theme.100');
}
</style>
