<template>
  <div class="rounded-md border border-blue-100 bg-white p-3 space-y-3">
    <div>
      <div class="text-sm font-medium text-gray-900">
        {{ question.title }}
      </div>
      <p
        v-if="question.description"
        class="mt-1 text-xs text-gray-500 whitespace-pre-wrap"
      >
        {{ question.description }}
      </p>
    </div>

    <div class="space-y-2">
      <div
        v-for="option in question.options"
        :key="option.id"
        class="rounded-md border bg-white"
        :class="isSelected(option.id) ? 'border-blue-400 bg-blue-50' : 'border-gray-200'"
      >
        <button
          type="button"
          class="w-full text-left p-2 flex items-start gap-2 disabled:cursor-not-allowed"
          :disabled="disabled"
          :data-testid="`question-option-${option.id}`"
          @click="toggleOption(option.id)"
        >
          <span
            class="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border text-[10px]"
            :class="[
              question.mode === 'single' ? 'rounded-full' : 'rounded',
              isSelected(option.id)
                ? 'border-blue-600 bg-blue-600 text-white'
                : 'border-gray-300 text-transparent',
            ]"
          >
            ✓
          </span>
          <span class="min-w-0">
            <span class="block text-sm font-medium text-gray-900">{{ option.label }}</span>
            <span
              v-if="option.summary"
              class="block text-xs text-gray-500 whitespace-pre-wrap"
            >
              {{ option.summary }}
            </span>
          </span>
        </button>
        <NCollapse
          v-if="option.details"
          class="border-t border-gray-100 px-2"
        >
          <NCollapseItem
            title="详情"
            :name="option.id"
          >
            <p class="text-xs text-gray-600 whitespace-pre-wrap pb-2">
              {{ option.details }}
            </p>
          </NCollapseItem>
        </NCollapse>
      </div>
    </div>

    <NInput
      v-if="question.allowCustom"
      v-model:value="customText"
      type="textarea"
      placeholder="补充说明（可选）"
      :autosize="{ minRows: 1, maxRows: 3 }"
      :disabled="disabled"
    />

    <div class="flex justify-end">
      <NButton
        size="small"
        type="primary"
        :disabled="!canSubmit"
        data-testid="question-submit"
        @click="submit"
      >
        提交回答
      </NButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NButton, NCollapse, NCollapseItem, NInput } from 'naive-ui'

import type { InteractiveQuestion, InteractiveQuestionAnswer } from '@/utils/interactiveMessage'

const props = defineProps<{ question: InteractiveQuestion; disabled?: boolean }>()
const emit = defineEmits<{ answer: [payload: InteractiveQuestionAnswer] }>()

const selectedOptionIds = ref<string[]>([])
const customText = ref('')

const canSubmit = computed(() => {
  if (props.disabled === true) return false
  if (selectedOptionIds.value.length > 0) return true
  return props.question.allowCustom && customText.value.trim() !== ''
})

watch(
  () => props.question.id,
  () => {
    selectedOptionIds.value = []
    customText.value = ''
  },
)

function isSelected(id: string) {
  return selectedOptionIds.value.includes(id)
}

function toggleOption(id: string) {
  if (props.disabled === true) return
  if (props.question.mode === 'single') {
    selectedOptionIds.value = [id]
    return
  }
  selectedOptionIds.value = isSelected(id)
    ? selectedOptionIds.value.filter((selected) => selected !== id)
    : [...selectedOptionIds.value, id]
}

function submit() {
  if (!canSubmit.value) return
  emit('answer', {
    question: props.question,
    selectedOptionIds: selectedOptionIds.value,
    customText: customText.value,
  })
}
</script>
