<script lang="ts" setup>
import { onResetUi, resetUi, toLabel, useService, vue } from '@factor/api'
import ElSpinner from '@factor/ui/ElSpinner.vue'
import ElButton from '@factor/ui/ElButton.vue'
import type { Site } from '../site'
import type { FactorSites } from '..'
import SiteEditorFrame from './SiteEditorFrame.vue'
import { tools } from './tools'

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

const loading = vue.ref(false)
const sending = vue.ref('')
const editing = vue.ref(false)
const editModes = [
  { name: 'Edit', value: `edit` },
  { name: 'Share', value: 'share' },
  { name: 'Integrations', value: 'integrations' },
] as const
type EditModes = typeof editModes[number]['value']

const activeEditMode = vue.computed<EditModes>({
  get: () => {
    const topic = factorRouter?.query.value.topic || 'edit'
    return topic as EditModes
  },
  set: async (v) => {
    await factorRouter?.replace({
      name: 'admin',
      params: { ...factorRouter?.params.value },
      query: { ...factorRouter?.query.value, topic: v },
    })
  },
})
const navItems = ['edit', 'deploy'] as const
type NavItem = typeof navItems[number]

const site = vue.computed<Site | undefined>(() => {
  return factorSites.activeSite.value
})

async function load() {
  loading.value = true
  await factorSites.loadSite({ siteId: factorRouter.query.value.siteId as string })
  loading.value = false
}

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

onResetUi(() => {
  editing.value = false
})

function onInput(ev: Event, field: 'title') {
  const target = ev.target as HTMLElement
  const v = target.innerHTML
  // updateFormUserConfig.value = { ...updateFormUserConfig.value, [field]: v }
}

async function save() {
  sending.value = 'save'

  await factorSites.activeSite.value?.requestManageSite({ _action: 'update' })

  sending.value = ''
}
</script>

<template>
  <div class="h-full w-full">
    <div v-if="loading" class="">
      <div class="text-theme-300 flex justify-center pt-32">
        <ElSpinner class="h-12 w-12" />
      </div>
    </div>
    <div v-else class="grid grid-flow-dense h-full grid-cols-[1fr] grid-rows-[auto_minmax(0,1fr)]">
      <div class="border-b border-theme-300 bg-theme-0">
        <div
          class="grid-cols-12 py-2 md:grid md:items-center md:justify-between px-4"
        >
          <div
            class="col-span-3 items-center flex text-sm lg:text-base space-x-4"
          >
            <ElButton
              btn="default"
              :href="factorRouter.link('admin').value"
            >
              <div class="i-tabler-home text-lg" />
            </ElButton>
            <div class="flex space-x-1 font-medium">
              <RouterLink
                class="text-theme-400 block pr-1 hover:text-primary-500"
                to="/"
              >
                Site /
              </RouterLink>

              <div
                class="hover:bg-theme-100 cursor-pointer rounded-md focus:outline-none"
                contenteditable="true"
                spellcheck="false"
                :value="site?.settings.title"
                @input="onInput($event, 'title')"
                @click.stop="editing = true"
                v-html="site?.settings.title || 'No Name'"
              />
            </div>
          </div>
          <div
            class="col-span-6 flex items-center justify-center space-x-2 "
          >
            <div
              v-for="(item, i) in editModes"
              :key="i"
              class="text-sm rounded-lg py-1.5 px-3 transition-colors font-semibold duration-75 cursor-pointer "
              :class="
                item.value === activeEditMode
                  ? `text-primary-600 bg-primary-100`
                  : `text-theme-600 hover:bg-theme-100 bg-theme-50`
              "
              @click.stop="site ? (activeEditMode = item.value) : ''"
            >
              {{ toLabel(item.value) }}
            </div>
          </div>
          <div
            class="col-span-3 flex items-center justify-end space-x-2 text-right text-sm"
          >
            <ElButton
              btn="primary"
              :loading="sending === 'save'"
              @click.prevent="save()"
            >
              Save Changes
            </ElButton>
          </div>
        </div>
      </div>

      <div
        v-if="site && ['edit'].includes(activeEditMode)"
        class="editor-work-area min-h-0 grid grid-flow-dense grid-cols-[60px_1fr] grid-rows-[minmax(0,1fr)]"
      >
        <div
          class="no-scrollbar min-w-0 grow-0 relative"
          @click.stop="resetUi({ scope: 'inputs', cause: 'clickEditorTools' })"
        >
          <div class="space-y-1 py-2 z-40 relative h-full bg-theme-0 border-r border-theme-300 ">
            <div
              v-for="(tool, i) in tools().filter(_ => _.isPrimary)"
              :key="i"
              class="flex items-center justify-center"
            >
              <div

                class=" space-x-2 cursor-pointer p-2 justify-end w-[40px] h-[40px] rounded-lg transition-all"
                :title="toLabel(tool.toolId)"
                :class="
                  factorSites.isUsingTool({ toolId: tool.toolId })
                    ? 'bg-primary-100 text-primary-600'
                    : 'text-theme-700 hover:bg-theme-100'"
                @click="factorSites.useTool({ toolId: tool.toolId })"
              >
                <div class="text-2xl" :class="tool.icon" />
              </div>
            </div>
          </div>
          <transition
            mode="out-in"
            enter-active-class="ease-out duration-200"
            enter-from-class="transform -translate-x-10 opacity-0"
            enter-to-class="transform translate-x-0 opacity-100"
            leave-active-class="ease-in duration-200"
            leave-from-class="transform translate-x-0 opacity-100"
            leave-to-class="transform -translate-x-10 opacity-0"
          >
            <div
              v-if="factorSites.activeTool.left.value"
              :key="factorSites.activeTool.left.value.toolId"
              class="absolute left-full h-full w-[300px] bg-theme-0 top-0 z-30 border-r shadow-[10px_0_8px_-5px_rgba(0,0,0,0.05)] border-theme-300 "
            >
              <component
                :is="factorSites.activeTool.left.value.el"
                v-bind="{
                  site,
                  tool: factorSites.activeTool.left.value,
                  ...factorSites.activeTool.left.value.props?.(site).value,
                }"
              />
            </div>
          </transition>
        </div>
        <div>
          <div class="h-full min-h-0 grid grid-flow-dense relative grid-rows-[minmax(0,1fr)] grid-cols-[1fr_minmax(250px,350px)]">
            <div
              v-if="['edit'].includes(activeEditMode)"
              class="cards relative flex h-full w-full flex-col justify-center overflow-scroll bg-theme-100"
              @click="factorSites.useTool({ toolId: '' })"
            >
              <!-- allow reset ui clicks over iframe (else iframe captures clicks) -->
              <div
                v-if="editing || factorSites.activeToolId.left.value"
                class="absolute inset-0 z-20 h-full w-full"
              />

              <SiteEditorFrame :site="site" />
            </div>

            <div class="no-scrollbar  bg-theme-0 border-l border-theme-300  relative">
              <transition
                mode="out-in"
                enter-active-class="ease-out duration-200"
                enter-from-class="transform scale-80 translate-y-4 opacity-0"
                enter-to-class="transform translate-y-0 opacity-100"
                leave-active-class="ease-in duration-200"
                leave-from-class="transform translate-y-0 opacity-100"
                leave-to-class="transform scale-80 translate-y-4 opacity-0"
              >
                <component
                  :is="factorSites.activeTool.right.value.el"
                  v-if="factorSites.activeTool.right.value"
                  :key="site.activeCard.value?.cardId"
                  v-bind="{
                    site,
                    tool: factorSites.activeTool.right.value,
                    ...factorSites.activeTool.right.value.props?.(site).value,
                  }"
                />
              </transition>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less">
.editor-work-area {

  .manager-area {
    --input-size: 13px;
    --input-bg: #ffffff;
  }
}
</style>
