<script setup lang="ts">
import {computed, ref} from 'vue';

import {Promotion} from '@element-plus/icons-vue';
import {ElButton, ElInput} from 'element-plus';

const props = defineProps<{
  loading?: boolean;
  placeholder?: string;
}>();

const emit = defineEmits<{
  send: [text: string];
  stop: [];
}>();

const text = ref('');
const canSend = computed(() => text.value.trim().length > 0 && !props.loading);

function send() {
  const value = text.value.trim();
  if (!value || props.loading) return;
  emit('send', value);
  text.value = '';
}

function stop() {
  if (!props.loading) return;
  emit('stop');
}

function handleKeydown(event: Event | KeyboardEvent) {
  if (!(event instanceof KeyboardEvent)) return;
  if (event.key !== 'Enter' || event.shiftKey) return;
  event.preventDefault();
  send();
}
</script>

<template>
  <div class="ai-prompt-input">
    <ElInput
      v-model="text"
      class="ai-prompt-input__textarea"
      type="textarea"
      resize="none"
      :autosize="{ minRows: 1, maxRows: 5 }"
      :disabled="loading"
      :placeholder="placeholder || '输入消息'"
      @keydown="handleKeydown"
    />
    <ElButton
      v-if="loading"
      type="primary"
      circle
      aria-label="中止"
      title="中止"
      class="ai-prompt-input__action is-stop"
      @click="stop"
    />
    <ElButton
      v-else
      type="primary"
      circle
      :icon="Promotion"
      :disabled="!canSend"
      aria-label="发送"
      class="ai-prompt-input__action"
      @click="send"
    />
  </div>
</template>

<style scoped>
.ai-prompt-input {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  padding: 10px;
  margin: 0 16px 16px;
  background: color-mix(in srgb, var(--el-bg-color) 92%, transparent);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-lighter);
}

.ai-prompt-input__textarea {
  flex: 1;
}

.ai-prompt-input__textarea :deep(.el-textarea__inner) {
  min-height: 36px !important;
  padding: 8px 10px;
  line-height: 20px;
  background: transparent;
  border: none;
  box-shadow: none;
}

.ai-prompt-input__action {
  width: 36px;
  height: 36px;
}

.ai-prompt-input__action.is-stop::before {
  display: block;
  width: 12px;
  height: 12px;
  content: '';
  background: var(--el-color-white);
  border-radius: 2px;
}
</style>
