<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEdit ? '編輯變體' : '新增變體'"
    width="440px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:modelValue', $event)"
    @closed="resetForm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      @submit.prevent
    >
      <el-form-item label="變體名稱" prop="name">
        <el-input v-model="form.name" placeholder="例：原始版本 / 紅色 CTA 版本" />
      </el-form-item>

      <el-form-item label="流量權重" prop="traffic_weight">
        <el-input-number
          v-model="form.traffic_weight"
          :min="0"
          :max="100"
          style="width: 100%"
        />
        <p style="color: #64748b; font-size: 12px; margin-top: 4px">
          各版本的流量比例，系統會依權重分配流量。
        </p>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="$emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submit">
        {{ isEdit ? "儲存" : "建立" }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref, watch } from "vue"
import { ElMessage } from "element-plus"
import variantApi from "@/module/variant/service/variant-api"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  experimentId: { type: String, default: "" },
  variant: { type: Object, default: null },
})

const emit = defineEmits(["update:modelValue", "saved"])

const isEdit = computed(() => Boolean(props.variant?.id))

const formRef = ref(null)
const saving = ref(false)

const defaultForm = () => ({
  name: "",
  traffic_weight: 0,
})

const form = ref(defaultForm())

const rules = {
  name: [{ required: true, message: "請填入變體名稱", trigger: "blur" }],
  traffic_weight: [{ required: true, message: "請設定流量權重", trigger: "blur" }],
}

watch(
  () => props.modelValue,
  (open) => {
    if (!open) return

    if (props.variant) {
      form.value = {
        name: props.variant.name || "",
        traffic_weight: props.variant.trafficWeight ?? props.variant.traffic_weight ?? 0,
      }
    } else {
      form.value = defaultForm()
    }
  }
)

const resetForm = () => {
  form.value = defaultForm()
  formRef.value?.clearValidate()
}

const submit = async () => {
  await formRef.value?.validate().catch(() => { throw new Error("validate") })

  saving.value = true
  try {
    const payload = {
      name: form.value.name,
      traffic_weight: form.value.traffic_weight,
    }

    let result
    if (isEdit.value) {
      result = await variantApi.updateVariant(props.variant.id, payload)
    } else {
      result = await variantApi.createVariant({
        ...payload,
        experiment_id: props.experimentId,
      })
    }

    ElMessage.success(isEdit.value ? "變體已更新" : "變體已建立")
    emit("update:modelValue", false)
    emit("saved", result)
  } catch (error) {
    ElMessage.error(error?.message || "操作失敗")
  } finally {
    saving.value = false
  }
}
</script>
