<script setup lang="ts">
interface ToolInfo {
  slug: string;
  name: string;
  type: string;
  description: string;
}

const props = defineProps<{
  isLoading: boolean;
  disabled?: boolean;
  placeholder?: string;
  enableTools: boolean;
  loggedIn: boolean;
}>();

const emit = defineEmits<{
  send: [content: string];
  stop: [];
  "update:enableTools": [val: boolean];
}>();

const inputText = ref("");
const textareaRef = ref<HTMLTextAreaElement | null>(null);
const availableTools = ref<ToolInfo[]>([]);

async function loadTools() {
  try {
    const res = await $fetch<{ code: number; data: ToolInfo[] }>("/api/llm/chat/tools");
    availableTools.value = res.data ?? [];
  } catch {
    availableTools.value = [];
  }
}

watch(
  () => props.enableTools,
  (val) => {
    if (val && availableTools.value.length === 0) {
      loadTools();
    }
  },
);

onMounted(() => {
  if (props.enableTools) {
    loadTools();
  }
});

function autoResize() {
  if (!textareaRef.value) return;
  textareaRef.value.style.height = "auto";
  const h = Math.min(textareaRef.value.scrollHeight, 200);
  textareaRef.value.style.height = h + "px";
}

watch(inputText, () => {
  nextTick(autoResize);
});

function handleSend() {
  const text = inputText.value.trim();
  if (!text || props.isLoading || props.disabled) return;
  emit("send", text);
  inputText.value = "";
  nextTick(autoResize);
}

function handleKeydown(e: KeyboardEvent) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    handleSend();
  }
}

defineExpose({
  setText(text: string) {
    inputText.value = text;
    nextTick(() => {
      autoResize();
      textareaRef.value?.focus();
    });
  },
  focus() {
    textareaRef.value?.focus();
  },
});
</script>

<template>
  <div class="agent-input">
    <!-- Tools bar above input -->
    <div v-if="loggedIn" class="tools-bar">
      <button
        class="toggle-btn"
        :class="{ active: enableTools }"
        title="工具调用"
        @click="emit('update:enableTools', !enableTools)"
      >
        <Icon name="lucide:wrench" />
        <span>工具</span>
      </button>
      <div v-if="enableTools && availableTools.length > 0" class="tools-list">
        <span
          v-for="t in availableTools"
          :key="t.slug"
          class="tool-chip"
          :title="t.description"
        >
          {{ t.name }}
        </span>
      </div>
    </div>

    <div class="input-wrapper">
      <textarea
        ref="textareaRef"
        v-model="inputText"
        class="agent-textarea"
        :placeholder="placeholder || '输入消息…（Enter 发送，Shift+Enter 换行）'"
        :disabled="disabled"
        rows="1"
        @keydown="handleKeydown"
      />
      <div class="input-actions">
        <button
          v-if="isLoading"
          class="btn-stop"
          @click="emit('stop')"
        >
          <Icon name="lucide:square" />
          停止
        </button>
        <button
          v-else
          class="btn-send"
          :disabled="!inputText.trim() || disabled"
          @click="handleSend"
        >
          <Icon name="lucide:arrow-up" />
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.agent-input {
  padding: 0 24px 20px;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.tools-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.toggle-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  background: var(--color-surface-soft);
  border: 1px solid var(--color-hairline);
  border-radius: 8px;
  font-size: 12px;
  color: var(--color-muted);
  cursor: pointer;
  transition: all 0.15s;
}

.toggle-btn:hover {
  border-color: var(--color-primary);
}

.toggle-btn.active {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: var(--color-on-primary);
}

.tools-list {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
}

.tool-chip {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  background: var(--color-surface-soft);
  border: 1px solid var(--color-hairline);
  border-radius: 6px;
  font-size: 11px;
  color: var(--color-muted);
  cursor: default;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  background: var(--color-surface-card);
  border: 1px solid var(--color-hairline);
  border-radius: 24px;
  padding: 8px 8px 8px 20px;
  transition: border-color 0.15s, box-shadow 0.15s;
}

.input-wrapper:focus-within {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(204, 120, 92, 0.12);
}

.agent-textarea {
  flex: 1;
  border: none;
  background: none;
  outline: none;
  resize: none;
  font-family: var(--font-body);
  font-size: 15px;
  line-height: 1.6;
  color: var(--color-ink);
  max-height: 200px;
  padding: 6px 0;
}

.agent-textarea::placeholder {
  color: var(--color-muted);
}

.agent-textarea:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.input-actions {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.btn-send,
.btn-stop {
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.15s;
}

.btn-send {
  width: 36px;
  height: 36px;
  background: var(--color-primary);
  color: var(--color-on-primary);
}

.btn-send:hover:not(:disabled) {
  background: var(--color-primary-active);
}

.btn-send:disabled {
  background: var(--color-hairline);
  color: var(--color-muted);
  cursor: not-allowed;
}

.btn-stop {
  width: 36px;
  height: 36px;
  background: var(--color-surface-dark);
  color: var(--color-on-dark);
  font-size: 12px;
  border-radius: 18px;
  padding: 0 12px;
  gap: 4px;
}

.btn-stop:hover {
  filter: brightness(1.2);
}
</style>
