<script lang="ts" setup>
import type { vue } from '@factor/api'
import { getNested, setNested } from '@factor/api'
import type { InputOption } from '@factor/ui'
import ElInput from '@factor/ui/ElInput.vue'
import ElToolSep from './ElToolSep.vue'

const props = defineProps({
  options: {
    type: Array as vue.PropType<InputOption[]>,
    required: true,
  },
  loading: { type: Boolean, default: false },
  modelValue: { type: Object as vue.PropType<Record<string, unknown>>, default: () => {} },
})

const emit = defineEmits<{
  (event: 'update:modelValue', payload: Record<string, unknown>): void
}>()

function isHidden(opt: InputOption) {
  return getNested({ path: opt.key, data: props.modelValue })
}
</script>

<template>
  <div class="gap-4 flex flex-col">
    <div
      v-for="(opt, i) in options"
      :key="i"
    >
      <div v-if="opt.input === 'group'">
        <div
          class="text-theme-400 hover:bg-theme-50 border-b border-theme-200 py-2 px-4 text-xs flex justify-between cursor-pointer"
          @click="emit('update:modelValue', setNested({ path: opt.key, data: modelValue, value: !getNested({ path: opt.key, data: modelValue }) }))"
        >
          <div class="font-semibold" v-html="opt.label" />
          <div class="text-lg">
            <div class="i-tabler-chevron-up transition-all" :class="!isHidden(opt) ? 'rotate-180' : ''" />
          </div>
        </div>
        <div class="p-4">
          <ToolForm
            :options="opt.options || []"
            :model-value="modelValue"
            @update:model-value="emit('update:modelValue', $event)"
          />
        </div>
      </div>

      <ElToolSep
        v-else-if="opt.input === 'title'"
        :text="opt.label"
        class="mb-2"
        :class="i === 0 ? 'mt-0' : 'mt-8'"
      />
      <div v-else>
        <ElInput
          class="setting-input"
          v-bind="opt.props.value"
          :input="opt.input"
          :model-value="getNested({ path: opt.key, data: modelValue })"
          @update:model-value="emit('update:modelValue', setNested({ path: opt.key, data: modelValue, value: $event }))"
        />
      </div>
    </div>
  </div>
</template>
