<template>
  <div class="answer-card">
    <h3 class="answer-title">我的答案</h3>
    <div class="upload-box">
      <input
        ref="fileInputRef"
        class="upload-input"
        type="file"
        accept="image/*"
        multiple
        @change="handleFileChange"
      />
      <div v-if="images.length === 0" class="upload-placeholder">
        <button class="upload-trigger" type="button" @click="openFilePicker">
          <div class="upload-btn">相机/上传</div>
          <p>请上传答案，最多3张图片</p>
        </button>
      </div>

      <template v-else>
        <div class="main-preview">
          <img :src="activeImage.url" :alt="activeImage.name" />
          <button class="delete-btn" type="button" @click="removeImage(activeIndex)">
            ×
          </button>
        </div>

        <div class="thumb-list">
          <button
            v-for="(image, index) in images"
            :key="image.url"
            class="thumb-item"
            :class="{ active: activeIndex === index }"
            type="button"
            @click="activeIndex = index"
          >
            <img :src="image.url" :alt="image.name" />
            <span class="thumb-delete" @click.stop="removeImage(index)">×</span>
          </button>

          <button
            v-if="images.length < maxImageCount"
            class="add-thumb"
            type="button"
            @click="openFilePicker"
          >
            +
          </button>
        </div>

        <div class="upload-tip">
          最多上传3张图片（已上传{{ images.length }}/3张）
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import type { UploadAnswerValue } from "@/views/AnswerQuestions/components/types";

const props = defineProps<{
  modelValue?: UploadAnswerValue[];
}>();

const emit = defineEmits<{
  (event: "update:modelValue", value: UploadAnswerValue[]): void;
}>();

const maxImageCount = 3;
const activeIndex = ref(0);
const fileInputRef = ref<HTMLInputElement>();

const images = computed(() => props.modelValue ?? []);
const activeImage = computed(() => images.value[activeIndex.value] ?? images.value[0]);

function openFilePicker() {
  fileInputRef.value?.click();
}

watch(
  images,
  (list: UploadAnswerValue[]) => {
    // 删除图片后，保证当前预览下标始终落在已有图片范围内
    if (activeIndex.value > list.length - 1) {
      activeIndex.value = Math.max(0, list.length - 1);
    }
  },
  { deep: true },
);

function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement;
  const files = Array.from(target.files ?? []);
  if (files.length === 0) return;

  const restCount = maxImageCount - images.value.length;
  const nextImages = files.slice(0, restCount).map((file) => ({
    name: file.name,
    // 这里先用本地预览 URL 模拟上传成功态，后续可替换接口返回地址
    url: URL.createObjectURL(file),
  }));

  emit("update:modelValue", [...images.value, ...nextImages]);
  activeIndex.value = images.value.length;
  target.value = "";
}

function removeImage(index: number) {
  const nextImages = images.value.filter(
    (_image: UploadAnswerValue, currentIndex: number) => currentIndex !== index,
  );
  emit("update:modelValue", nextImages);
}
</script>

<style scoped lang="scss">
.answer-card {
  flex: 1;
  border-radius: 18px;
  background: #fff;
  padding: 0 32px;
}

.answer-title {
  font-size: 40px;
  color: #2f333a;
  margin-bottom: 20px;
  // padding-left: 8px;
}

.upload-box {
  margin-top: 2px;
  flex: 1;
  border-radius: 14px;
  background: transparent;
  display: flex;
  flex-direction: column;
  color: var(--color-text-brand);
  font-size: 24px;
  gap: 24px;
  overflow-y: auto;
}

.upload-input {
  display: none;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  text-align: center;
  color: #666;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 520px;
  border: 2px solid #2b9be5;
  border-radius: 14px;

  p {
    margin-top: 20px;
    color: #666;
    font-size: 26px;
    line-height: 1;
  }
}

.upload-btn {
  height: 64px;
  min-width: 190px;
  border-radius: 32px;
  padding: 0 34px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: #e9f3ff;
  color: #2f80ed;
  font-size: 34px;
  font-weight: 600;
}

.upload-trigger {
  border: none;
  background: transparent;
  padding: 0;
  margin: 0;
  cursor: pointer;
  text-align: center;
}

.main-preview {
  position: relative;
  width: 100%;
  height: 320px;
  border: 2px solid #b9d6f4;
  border-radius: 14px;
  overflow: hidden;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }
}

.delete-btn,
.thumb-delete {
  position: absolute;
  border: 2px solid #6d7485;
  border-radius: 50%;
  background: #fff;
  color: #4d5568;
  font-weight: 700;
  line-height: 1;
  cursor: pointer;
}

.delete-btn {
  top: 12px;
  right: 12px;
  width: 34px;
  height: 34px;
  font-size: 28px;
}

.thumb-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 24px;
}

.thumb-item,
.add-thumb {
  position: relative;
  width: 144px;
  height: 96px;
  border-radius: 10px;
  background: #f6f8fb;
  border: 1px solid #e1e8f2;
  padding: 0;
  overflow: hidden;
  cursor: pointer;

  &.active {
    border: 2px solid #2b80ea;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }
}

.thumb-delete {
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  font-size: 20px;
}

.add-thumb {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #aac8ec;
  color: var(--color-text-brand);
  font-size: 42px;
}

.upload-tip {
  height: 46px;
  border-radius: 8px;
  background: #fff9e8;
  color: #d99427;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
