<template>
  <div class="inline-block text-[0px] rounded-lg overflow-hidden w-70 mr-3">
    <div class="bg-sky-500/5 border border-gray-200 rounded-t-lg flex items-center px-3 py-2.5 min-h-11">
      <van-icon class="minus uni-color" color="opacity" size="22" type="minus" />
      <span class="ml-2 text-base font-medium text-[#0ccd58] flex-1 truncate">{{ title ||
        t("common.form.visitorDefault") }}</span>
      <van-icon v-if="showDeleteIcon" class="delete uni-color" color="opacity" size="22" type="trash"
        @click="handleDelete" />
    </div>
    <div class="bg-gray-100 rounded-b-lg border border-t-0 border-gray-200 p-3">
      <div class="flex items-start flex-col relative mb-4">
        <div class="flex items-center w-full">
          <span class="text-sm text-[#86909c] w-[50px] shrink-0 font-medium mr-2.5">{{ t("common.form.name")
            }}</span>
          <input
            class="flex-1 text-sm text-gray-800 border-none border-b border-gray-200 bg-transparent outline-none transition-all duration-200 ease-in-out min-h-5 placeholder:text-[#86909c] placeholder:opacity-80 focus:border-b focus:border-gray-200"
            :class="{ 'border-b border-[#ff4d4f]': nameError }" v-model="nameValue"
            :placeholder="t('common.form.namePlaceholder')" @blur="validateName" />
        </div>
        <span v-if="nameError" class="text-xs text-[#ff4d4f] mt-1.5 ml-[60px] leading-relaxed">{{ nameError }}</span>
      </div>
      <div class="flex items-start flex-col relative">
        <div class="flex items-center w-full">
          <span class="text-sm text-[#86909c] w-[50px] shrink-0 font-medium mr-2.5">{{ t("common.form.phone")
            }}</span>
          <input
            class="flex-1 text-sm text-gray-800 border-none border-b border-gray-200 bg-transparent outline-none transition-all duration-200 ease-in-out min-h-5 placeholder:text-[#86909c] placeholder:opacity-80 focus:border-b focus:border-gray-200"
            :class="{ 'border-b border-[#ff4d4f]': phoneError }" v-model="phoneValue"
            :placeholder="t('common.form.phonePlaceholder')" type="tel" maxlength="11" @blur="validatePhone" />
        </div>
        <span v-if="phoneError" class="text-xs text-[#ff4d4f] mt-1.5 ml-[60px] leading-relaxed">{{ phoneError }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

// 常量定义
const PHONE_REGEX = /^1[3-9]\d{9}$/;
const ERROR_MESSAGES = {
  NAME_REQUIRED: "common.form.namePlaceholder",
  PHONE_REQUIRED: "common.form.phonePlaceholder",
  PHONE_INVALID: "booking.validation.validPhone",
};

/**
 * FormCard 组件 Props
 * @typedef {Object} FormCardProps
 * @property {string} title - 表单标题
 * @property {Object} form - 表单数据对象
 * @property {string} form.visitorName - 姓名
 * @property {string} form.contactPhone - 手机号
 * @property {boolean} showDeleteIcon - 是否显示删除图标
 */
const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  form: {
    type: Object,
    default: () => ({
      visitorName: "",
      contactPhone: "",
    }),
    validator: (value) => {
      return (
        value &&
        typeof value === "object" &&
        "visitorName" in value &&
        "contactPhone" in value
      );
    },
  },
  showDeleteIcon: {
    type: Boolean,
    default: true,
  },
});

/**
 * FormCard 组件事件
 * @typedef {Object} FormCardEmits
 * @property {Function} update:visitorName - 更新姓名事件
 * @property {Function} update:contactPhone - 更新手机号事件
 * @property {Function} delete - 删除表单事件
 */
const emit = defineEmits([
  "update:visitorName",
  "update:contactPhone",
  "delete",
]);

// 响应式状态
const nameError = ref("");
const phoneError = ref("");

// 计算属性 - 双向绑定
const nameValue = computed({
  get: () => props.form?.visitorName || "",
  set: (value) => emit("update:visitorName", value?.trim() || ""),
});

const phoneValue = computed({
  get: () => props.form?.contactPhone || "",
  set: (value) => {
    // 只允许数字输入
    const numericValue = value.replace(/\D/g, "");
    emit("update:contactPhone", numericValue);
  },
});

// 工具函数
/**
 * 验证姓名是否有效
 * @param {string} name - 姓名
 * @returns {string} 错误信息，空字符串表示验证通过
 */
const getNameError = (name) => {
  if (!name || name.trim() === "") {
    return t(ERROR_MESSAGES.NAME_REQUIRED);
  }
  return "";
};

/**
 * 验证手机号是否有效
 * @param {string} phone - 手机号
 * @returns {string} 错误信息，空字符串表示验证通过
 */
const getPhoneError = (phone) => {
  if (!phone) {
    return t(ERROR_MESSAGES.PHONE_REQUIRED);
  }
  if (!PHONE_REGEX.test(phone)) {
    return t(ERROR_MESSAGES.PHONE_INVALID);
  }
  return "";
};

// 验证方法
const validateName = () => {
  nameError.value = getNameError(props.form?.visitorName);
};

const validatePhone = () => {
  phoneError.value = getPhoneError(props.form?.contactPhone);
};

// 事件处理
const handleDelete = () => {
  emit("delete");
};

// 暴露给模板的方法（用于测试或外部调用）
defineExpose({
  validateName,
  validatePhone,
  getNameError,
  getPhoneError,
});
</script>
