<script setup lang="ts">
import {ArrowUpIcon, Loader2} from "lucide-vue-next"
import {
    InputGroup,
    InputGroupAddon,
    InputGroupButton,
    InputGroupTextarea
} from "@/Packages/Shadcn/Components/ui/input-group"
import {computed, nextTick} from "vue";

const emit = defineEmits(['submit'])

const { disabled } = defineProps({
    loading: {
        type: Boolean,
        default: false
    },

    disabled: {
        type: Boolean,
        default: false
    },
})

const value = defineModel({required: true, default: String})

const isEmpty = computed(() => String(value.value ?? '').trim().length === 0)

const submit = () => {
    if (disabled || isEmpty.value) return

    emit('submit', value.value)
}

const handleEnter = e => {
    if (e.metaKey || e.ctrlKey || e.shiftKey) {
        const {selectionStart, selectionEnd, value} = e.target
        value.value = value.slice(0, selectionStart) + '\n' + value.slice(selectionEnd)
        nextTick(() => {
            const pos = selectionStart + 1
            e.target.setSelectionRange(pos, pos)
        })
    } else submit()
}
</script>

<template>
    <InputGroup class="!bg-card">
        <InputGroupTextarea placeholder="Ask, Search or Chat..." v-model="value"
                            @keydown.enter.prevent="handleEnter"/>
        <InputGroupAddon align="block-end">
            <InputGroupButton class="ml-auto cursor-pointer" variant="default" :disabled="disabled || isEmpty"
                              @click="submit">
                <template v-if="!loading">
                    <ArrowUpIcon class="size-5"/>
                    <span>Отправить</span>
                </template>
                <template v-else>
                    <Loader2 class="w-4 h-4 animate-spin"/>
                    <span>Отправка</span>
                </template>
            </InputGroupButton>
        </InputGroupAddon>
    </InputGroup>
</template>

<style scoped>

</style>
