<template>
  <div class="activity-edit-page">
    <van-nav-bar
      :title="isEdit ? '编辑活动' : '创建活动'"
      left-text="取消"
      left-arrow
      @click-left="onClickLeft"
    />

    <van-form @submit="onSubmit">
      <van-cell-group inset style="margin-top: 16px;">
        <van-field
          v-model="form.title"
          name="title"
          label="标题"
          placeholder="活动标题"
          :rules="[{ required: true, message: '必填' }]"
        />
        <van-field
          v-model="form.description"
          name="description"
          label="简介"
          type="textarea"
          placeholder="活动简介"
          autosize
        />
        <van-field
          v-model="form.location"
          name="location"
          label="地点"
          placeholder="活动地点"
          :rules="[{ required: true, message: '必填' }]"
        />
        <van-field
          v-model="form.category"
          name="category"
          label="分类"
          placeholder="例如：音乐, 体育"
        />
        
        <van-field
          v-model="form.startTime"
          is-link
          readonly
          name="startTime"
          label="开始时间"
          placeholder="点击选择时间"
          @click="showStartTimePicker = true"
          :rules="[{ required: true, message: '必填' }]"
        />
        <van-popup v-model:show="showStartTimePicker" position="bottom">
           <van-date-picker
            v-model="pickerValues.startDate"
            title="选择日期"
            @confirm="onConfirmStartDate"
            @cancel="showStartTimePicker = false"
           />
        </van-popup>
        <van-popup v-model:show="showStartTimeTimePicker" position="bottom">
           <van-time-picker
            v-model="pickerValues.startTime"
            title="选择时间"
            @confirm="onConfirmStartTime"
            @cancel="showStartTimeTimePicker = false"
           />
        </van-popup>

        <van-field
          v-model="form.endTime"
          is-link
          readonly
          name="endTime"
          label="结束时间"
          placeholder="点击选择时间"
          @click="showEndTimePicker = true"
          :rules="[{ required: true, message: '必填' }]"
        />
        <van-popup v-model:show="showEndTimePicker" position="bottom">
           <van-date-picker
            v-model="pickerValues.endDate"
            title="选择日期"
            @confirm="onConfirmEndDate"
            @cancel="showEndTimePicker = false"
           />
        </van-popup>
        <van-popup v-model:show="showEndTimeTimePicker" position="bottom">
           <van-time-picker
            v-model="pickerValues.endTime"
            title="选择时间"
            @confirm="onConfirmEndTime"
            @cancel="showEndTimeTimePicker = false"
           />
        </van-popup>

        <van-field
          name="maxParticipants"
          label="最大人数"
        >
          <template #input>
            <van-stepper v-model="form.maxParticipants" min="1" max="10000" integer />
          </template>
        </van-field>

        <van-field name="status" label="状态" v-if="isEdit">
           <template #input>
            <van-radio-group v-model="form.status" direction="horizontal">
              <van-radio :name="0">草稿</van-radio>
              <van-radio :name="1">发布</van-radio>
              <van-radio :name="3">结束</van-radio>
              <van-radio :name="4">取消</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 32px 16px;">
        <van-button round block type="primary" native-type="submit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { createActivity, updateActivity, getActivityDetail } from '@/services/activity';
import { showToast } from 'vant';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();

const isEdit = computed(() => !!route.params.id);
const id = Number(route.params.id);
const loading = ref(false);

const showStartTimePicker = ref(false);
const showEndTimePicker = ref(false);
const showStartTimeTimePicker = ref(false);
const showEndTimeTimePicker = ref(false);
const tempDate = ref<string[]>([]);

const pickerValues = reactive({
  startDate: dayjs().format('YYYY-MM-DD').split('-'),
  startTime: dayjs().format('HH:mm').split(':'),
  endDate: dayjs().format('YYYY-MM-DD').split('-'),
  endTime: dayjs().format('HH:mm').split(':'),
});

const form = reactive({
  title: '',
  description: '',
  location: '',
  category: '',
  startTime: '',
  endTime: '',
  maxParticipants: 100,
  status: 0,
});

const onClickLeft = () => history.back();

onMounted(async () => {
  if (isEdit.value) {
    try {
      const res = await getActivityDetail(id);
      Object.assign(form, res);
      // Format time for display in native format if needed, but here we keep string
      // Just ensure it's displayable. The field displays standard string.
      // If comes from API, it is usually ISO.
      // Let's format it to friendly string for Vant inputs? 
      // Actually our inputs are text type (readonly), displaying the string directly.
      if (form.startTime) {
        const start = dayjs(form.startTime);
        form.startTime = start.format('YYYY-MM-DD HH:mm:ss');
        pickerValues.startDate = start.format('YYYY-MM-DD').split('-');
        pickerValues.startTime = start.format('HH:mm').split(':');
      }
      if (form.endTime) {
        const end = dayjs(form.endTime);
        form.endTime = end.format('YYYY-MM-DD HH:mm:ss');
        pickerValues.endDate = end.format('YYYY-MM-DD').split('-');
        pickerValues.endTime = end.format('HH:mm').split(':');
      }
    } catch (error) {
       showToast('加载失败');
    }
  }
});

const onConfirmStartDate = ({ selectedValues }: any) => {
  tempDate.value = selectedValues;
  showStartTimePicker.value = false;
  showStartTimeTimePicker.value = true;
};

const onConfirmStartTime = ({ selectedValues }: any) => {
  const dateStr = tempDate.value.join('-');
  const timeStr = selectedValues.join(':') + ':00';
  form.startTime = `${dateStr} ${timeStr}`;
  showStartTimeTimePicker.value = false;
};

const onConfirmEndDate = ({ selectedValues }: any) => {
  tempDate.value = selectedValues;
  showEndTimePicker.value = false;
  showEndTimeTimePicker.value = true;
};

const onConfirmEndTime = ({ selectedValues }: any) => {
  const dateStr = tempDate.value.join('-');
  const timeStr = selectedValues.join(':') + ':00';
  form.endTime = `${dateStr} ${timeStr}`;
  showEndTimeTimePicker.value = false;
};

const onSubmit = async () => {
  loading.value = true;
  try {
    // Ensure ISO format
    // Ensure valid format
    if (!form.startTime || !form.endTime) {
       showToast('请选择完整的时间');
       loading.value = false;
       return;
    }

    const data = {
      ...form,
      maxParticipants: Number(form.maxParticipants),
      startTime: dayjs(form.startTime).format('YYYY-MM-DDTHH:mm:ss'),
      endTime: dayjs(form.endTime).format('YYYY-MM-DDTHH:mm:ss')
    };
    
    if (isEdit.value) {
      await updateActivity(id, data);
      showToast('已更新');
    } else {
      await createActivity(data);
      showToast('已创建');
    }
    router.back();
  } catch (error) {
    // Error handled
  } finally {
    loading.value = false;
  }
};
</script>


<style scoped lang="scss">
.activity-edit-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}
</style>
