<template>
  <div class="max-w-screen-md w-full flex flex-col space-y-4 p-6">
    <UCard
      class="transition-[box-shadow] hover:ring-2 has-[textarea:focus]:ring-2 has-[textarea:focus]:ring-primary-500 dark:has-[textarea:focus]:ring-primary-400"
      :ui="cardUI"
    >
      <UTextarea
        v-model="query"
        name="createInput"
        autoresize
        placeholder="输入搜索内容..."
        :rows="5"
        variant="none"
        :padded="false"
        maxlength="2000"
      />
      <div class="flex justify-between items-center">
        <div class="flex items-center gap-2">
<!--          <UTooltip class="relative" :text="isPro ? '已开启专家搜索' : '已关闭专家搜索'" :shortcuts="[metaSymbol, 'O']">-->
<!--            <div-->
<!--              v-show="!isPro"-->
<!--              class="absolute w-7 h-0.5 rotate-45 top-3.5 left-1 bg-gray-700 dark:bg-gray-200 hover:bg-gray-900 dark:hover:bg-white rounded"/>-->
<!--            <UButton-->
<!--              :ui="{ rounded: 'rounded-full' }"-->
<!--              :icon="isPro ? 'i-heroicons-sparkles-20-solid' : 'i-heroicons-sparkles-20-solid'"-->
<!--              color="gray"-->
<!--              variant="ghost"-->
<!--              @click="handleTogglePro"-->
<!--            />-->
<!--          </UTooltip>-->
          <USelectMenu
            v-model="selectedRepo"
            :ui-menu="menuUI"
            :options="$repos"
            placeholder="选择 GitHub 项目"
            value-attribute="label"
            option-attribute="label"
          >
            <UTooltip v-if="!selectedRepo" :text="isPro ? '选择 GitHub 项目' : '选择 GitHub 项目（需开启专家搜索）'">
              <UButton
                :ui="{ rounded: 'rounded-full' }"
                icon="i-simple-icons-github"
                color="gray"
                variant="ghost"
                :disabled="!isPro"
              />
            </UTooltip>

            <UButton v-else color="gray" variant="ghost" :class="{ 'group': selectedRepo }">
              <UIcon name="i-simple-icons-github"/>
              <span>{{ selectedRepo }}</span>
              <UIcon name="i-heroicons-chevron-down-20-solid" class="text-xl flex group-hover:hidden"/>
              <UButton
                v-if="selectedRepo"
                class="hidden group-hover:flex"
                icon="i-heroicons-x-mark-20-solid"
                :padded="false"
                color="gray"
                variant="link"
                @click.stop.prevent="handleClearRepo"
              />
            </UButton>
          </USelectMenu>
        </div>
        <UTooltip text="搜索" :shortcuts="[metaSymbol, '↵']" :prevent="query === ''">
          <UButton
            :ui="{ rounded: 'rounded-full' }"
            icon="i-heroicons-chevron-right-20-solid"
            :loading="loading"
            :disabled="query === ''"
            size="md"
            @click="handleSearch"
          />
        </UTooltip>
      </div>
    </UCard>
  </div>
</template>
<script setup>
const { $repos } = storeToRefs(useReposStore())
const { $setRepo } = useReposStore()
const { $setFirstRecordTitle } = useSearchStore()
const { metaSymbol } = useShortcuts()
const emits = defineEmits([ 'search' ])
const query = ref('')
const selectedRepo = ref('')
const loading = ref(false)
const cardUI = {
  body: {
    padding: 'p-3 sm:p-3'
  },
  rounded: 'rounded-xl'
}
const menuUI = {
  width: 'w-auto'
}
const isPro = ref(true)

const handleSearch = async () => {
  if (loading.value || query.value === '') return
  loading.value = true
  const currentRepo = $repos.value.find(item => item.label === selectedRepo.value)
  const repo_path = currentRepo ? currentRepo.url : ''
  const body = {
    title: query.value,
    repo_path: repo_path || ''
  }
  const { data, error } = await useRequest('/v1/chat/completion/create', { method: 'post', body })
  loading.value = false
  if (error.value) return
  // todo 临时存到pina给搜索使用
  $setFirstRecordTitle(query.value)
  navigateTo(`/search/${data.value.data.c_id}`)
  emits('search')
}
function handleQuickSearch (title) {
  query.value = title
  handleSearch()
}
defineExpose({
  handleQuickSearch
})
function handleClearRepo () {
  selectedRepo.value = ''
}
nextTick(async () => {
  if (!$repos.value.length) {
    const { data } = await useRequest('/v1/chat/repository')
    const repoData = data.value.data.map(item => {
      return {
        label: item.name,
        url: item.path,
        branch: item.branch
      }
    })
    $setRepo(repoData)
  }
})

defineShortcuts({
  meta_enter: {
    usingInput: 'createInput',
    handler: () => {
      handleSearch()
    }
  },
  meta_o: {
    usingInput: 'createInput',
    handler: () => {
      handleTogglePro()
    }
  }
})

function handleTogglePro () {
  isPro.value = !isPro.value
  if (!isPro.value) handleClearRepo()
}
</script>
