<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-green-500 dark:has-[textarea:focus]:ring-green-400"
            :ui="cardUI"
        >
            <UTextarea
                name="createInput"
                v-model="query"
                autoresize
                placeholder="输入搜索内容..."
                :rows="5"
                variant="none"
                :padded="false"
            />
            <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" trailing-icon="i-heroicons-chevron-down-20-solid" :label="selectedRepo || '选择 GitHub 项目'" />
                </USelectMenu>
                <UButton
                    trailing-icon="i-heroicons-chevron-right-20-solid"
                    @click="handleSearch"
                    :loading="loading"
                    :disabled="query === ''"
                >搜索</UButton>
            </div>
        </UCard>
    </div>
</template>
<script setup>
const { $setRepo } = useReposStore()
const { $repos } = storeToRefs(useReposStore())
const emits = defineEmits([ 'search' ])
const query = ref('')
const selectedRepo = ref('keycloak')
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 result = await useRequest('/v1/chat/completion/create', {
        method: 'post',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    if (result && result.data) {
        navigateTo(`/search/${result.data.c_id}?query=${query.value}&repo=${selectedRepo.value}`)
        emits('search')
        nextTick(() => {
            loading.value = false
        })
    }    
}
onMounted(async () => {
    if (!$repos.length) {
        let repoData = await fetchRequest('/v1/chat/repository', {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        repoData = repoData.data.map(item => {
            return {
                label: item.name,
                url: item.path,
                branch: item.branch
            }
        })
        $setRepo(repoData)
    }
})

defineShortcuts({
    meta_enter: {
        usingInput: 'createInput',
        handler: () => {
            handleSearch()
        }
    }
})
</script>
