<script lang="ts" setup>
import ElPanel from '@factor/ui/ElPanel.vue'
import ElIndexGrid from '@factor/ui/ElIndexGrid.vue'
import type { ActionItem, IndexItem, IndexMeta } from '@factor/api'
import { standardDate, useService, vue } from '@factor/api'

import type { Site } from '../site'
import type { FactorSites } from '..'
import ElSiteStart from './ElSiteStart.vue'

const { factorRouter, factorSites } = useService<{ factorSites: FactorSites }>()

const showCreateModal = vue.ref(false)

const loading = vue.ref(false)
const items = vue.shallowRef<Site[]>([])
const indexMeta = vue.ref<IndexMeta>()
async function loadIndex() {
  loading.value = true
  const r = await factorSites.requestIndex()
  items.value = r.items || []
  indexMeta.value = r.indexMeta
  loading.value = false
}

vue.onMounted(async () => {
  await loadIndex()
})

const formattedData = vue.computed<IndexItem[]>(() => {
  if (!items.value)
    return []

  const rows = items.value.map((item) => {
    const domain = item.settings.domain || `https://${item.settings.slug}.fiction.com`
    const displayDomain = domain.replace('https://', '').replace('http://', '')
    const out: IndexItem = {
      name: item.settings.title || 'Untitled',
      key: item.settings.siteId,
      links: [{ name: displayDomain, href: domain, target: '_blank', class: 'underline', icon: 'i-tabler-world' }, { name: `Created ${standardDate(item.settings.createdAt)}` }],
      actions: [
        { name: 'Edit Website', btn: 'primary', href: factorRouter.link('admin', { viewId: 'siteEdit' }, { siteId: item.settings.siteId }).value },
        { name: 'Site Settings', btn: 'default', href: factorRouter.link('admin', { viewId: 'siteSettings' }, { siteId: item.settings.siteId }).value },
      ],
      fig: vue.defineAsyncComponent(() => import('./fig/FigSite.vue')),
    }

    return out
  })

  return rows
})

const actions: ActionItem[] = [{ name: 'Create New Website', btn: 'primary', onClick: () => { showCreateModal.value = true } }]
</script>

<template>
  <ElPanel title="Your Websites" :actions="actions">
    <div class="p-4">
      <ElIndexGrid
        :loading="loading"
        :list="formattedData"
        :index-meta="{}"
        :edit-actions="[]"
        :empty="{
          title: 'Your Personal Website',
          description: `Build your audience`,
          actions,
          fig: vue.defineAsyncComponent(() => import('./fig/FigSite.vue')),
        }"
        :actions="[]"
        :on-item-click="() => {}"
        @bulk-edit="() => {}"
      />
    </div>
    <ElSiteStart :vis="showCreateModal" />
  </ElPanel>
</template>
../site
