<script lang="ts" setup>
import { toLabel, vue } from '@factor/api'
import ElInput from '@factor/ui/ElInput.vue'
import type { CardTemplate } from '../card'
import type { Site } from '../site'
import type { EditorTool } from './tools'
import ElTool from './ElTool.vue'

const props = defineProps({
  site: {
    type: Object as vue.PropType<Site>,
    required: true,
  },
  tool: {
    type: Object as vue.PropType<EditorTool>,
    required: true,
  },
})
const control = props.site.settings.factorSites
const groupTemplates = vue.computed(() => {
  const all = props.site.theme.value?.cardTemplates

  const grouped: Record<string, CardTemplate[]> = {}

  if (all) {
    all.forEach((template) => {
      template.settings.category?.forEach((cat) => {
        if (!grouped[cat])
          grouped[cat] = []

        grouped[cat].push(template)
      })
    })
  }
  return grouped
})

function addCard(args: { templateKey: string }) {
  const { templateKey = 'page' } = args
  props.site.addCard({ templateKey, delay: 400 })
  control.useTool({ toolId: 'layout' })
}
</script>

<template>
  <ElTool :tool="tool">
    <div class="p-4">
      <ElInput
        label="Add Element To"
        input="InputSelectCustom"
        :list="site.regionKeys"
        class="mb-8"
        :model-value="site.activeRegionKey.value"
        @update:model-value="site.activeRegionKey.value = $event"
      />
      <div class="space-y-4">
        <div v-for="(tplGroup, i) in groupTemplates" :key="i">
          <div class="text-xs font-semibold text-theme-300 mb-2 tracking-wider uppercase">
            {{ toLabel(i) }}
          </div>
          <div class="space-y-2">
            <div
              v-for="(item, ii) in tplGroup"
              :key="ii"
              class="flex shadow-sm group cursor-pointer hover:shadow hover:-translate-y-0.5 transition-all rounded-md"
              @click="addCard({ templateKey: item.settings.templateKey })"
            >
              <div class="px-3 py-1 text-3xl flex justify-center items-center border rounded-l-md border-theme-300 group-hover:border-theme-300 bg-theme-0" :class="item.settings.iconStyle ? item.settings.iconStyle : 'text-primary-500' ">
                <div :class="item.settings.icon" />
              </div>
              <div class="px-3 py-2 flex items-center grow rounded-r-md border-y border-r border-theme-300 group-hover:bg-theme-100 bg-theme-50">
                <div class=" leading-tight">
                  <div class="font-semibold text-sm text-theme-700">
                    {{ item.settings.title }}
                  </div>
                  <div class="text-xs font-normal text-theme-400">
                    {{ item.settings.description }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </ElTool>
</template>
