<template>
  <van-dialog
    v-model:show="visible"
    title="评价活动"
    show-cancel-button
    :before-close="handleBeforeClose"
    @confirm="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="review-form">
      <div class="form-item">
        <label>评分</label>
        <van-rate v-model="formData.rating" :count="5" color="#ffd21e" void-icon="star" void-color="#eee" />
      </div>
      <div class="form-item">
        <label>评论内容（可选）</label>
        <van-field
          v-model="formData.content"
          rows="4"
          autosize
          type="textarea"
          maxlength="500"
          placeholder="请输入您的评价..."
          show-word-limit
        />
      </div>
    </div>
  </van-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { submitReview } from '@/services/review';
import { showToast } from 'vant';

interface Props {
  show: boolean;
  activityId: number;
}

interface Emits {
  (e: 'update:show', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const visible = ref(false);
const formData = ref({
  rating: 5,
  content: ''
});

watch(() => props.show, (newVal) => {
  visible.value = newVal;
  if (newVal) {
    // Reset form when dialog opens
    formData.value = {
      rating: 5,
      content: ''
    };
  }
});

watch(visible, (newVal) => {
  if (!newVal) {
    emit('update:show', false);
  }
});

const handleBeforeClose = (action: string) => {
  if (action === 'confirm') {
    return true; // Allow close, handleSubmit will be called
  }
  return true; // Allow cancel
};

const handleSubmit = async () => {
  if (formData.value.rating === 0) {
    showToast('请选择评分');
    return false;
  }

  try {
    await submitReview({
      activityId: props.activityId,
      rating: formData.value.rating,
      content: formData.value.content || undefined
    });
    showToast('评价成功');
    emit('success');
    visible.value = false;
  } catch (error) {
    // Error handled by interceptor
  }
};

const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss">
.review-form {
  padding: 20px;

  .form-item {
    margin-bottom: 20px;

    label {
      display: block;
      margin-bottom: 10px;
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}
</style>
