<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
                name="createInput"
                v-model="query"
                autoresize
                placeholder="输入搜索内容..."
                :rows="5"
                variant="none"
                :padded="false"
                maxlength="2000"
            />
            <div class="flex justify-between">
                <USelectMenu
                    :ui-menu="menuUI"
                    v-model="selectedRepo"
                    :options="$repos"
                    placeholder="选择 GitHub 项目"
                    value-attribute="label"
                    option-attribute="label"
                >
                    <UButton color="gray" variant="ghost" :class="{ 'group': selectedRepo }">
                        <span>{{ selectedRepo || '选择 GitHub 项目' }}</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"
                            @click.stop.prevent="handleClearRepo"
                            icon="i-heroicons-x-mark-20-solid"
                            :padded="false"
                            color="gray"
                            variant="link"
                        />
                    </UButton>
                </USelectMenu>
                <UButton
                    trailing-icon="i-heroicons-chevron-right-20-solid"
                    @click="handleSearch"
                    :loading="loading"
                    :disabled="query === ''"
                    label="搜索"
                />
            </div>
        </UCard>
    </div>
</template>
<script setup>
const { $repos } = storeToRefs(useReposStore())
const { $setRepo } = useReposStore()
const { $setFirstRecordTitle, $setSearchHistory } = useSearchStore()
const emits = defineEmits([ 'search' ])
const query = ref('')
const selectedRepo = ref('')
const loading = ref(false)
const cardUI = {
    body: {
        padding: 'p-4 sm:p-4'
    },
    rounded: 'rounded-xl'
}
const menuUI = {
    width: 'w-auto'
}

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 { data, error } = await useRequest('/v1/chat/completion/create', { 
        method: 'post',
        body: {
            repo_path,
            title: query.value
        }
    })
    loading.value = false
    if (error.value) return
    // todo 临时存到pina给搜索使用
    $setFirstRecordTitle(query.value)
    $setSearchHistory({
        title: query.value,
        c_id: data.value.data.c_id
    })
    navigateTo(`/search/${data.value.data.c_id}`)
    emits('search')
}
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()
        }
    }
})
</script>
