<template>
  <div class="apply-container">
    <div class="banner">
      <div class="slogan">BLOOM YOUR CREATIVITY • AiDA GLOBAL FASHION AWARD 2026</div>
      <div class="title">Application Form</div>
      <div class="form-header">
        <div class="form-title">Email Verification</div>
        <div class="desc">AiDA Users Only</div>
      </div>
    </div>
    <div class="form-container">
      <div class="form-content">
        <a-form
          name="form"
          ref="formRef"
          layout="vertical"
          :model="form"
          :rules="rulesRef"
          autocomplete="off"
        >
          <div class="email-box full-row">
            <a-form-item name="email" required label="Email Address">
              <div class="email-wrapper flex align-center">
                <a-input v-model:value="form.email" />
                <div class="code-btn" @click="handleSendCode">Send Code</div>
              </div>
              <div class="tips">
                Please use the email address you registered with AiDA.
              </div>
            </a-form-item>
          </div>

          <template v-for="item in formKeys" :key="item.key">
            <a-form-item
              v-if="item.key !== 'email'"
              :required="item.required"
              :label="item.label"
              :name="item.key"
            >
              <a-input v-model:value="form[item.key]" />
            </a-form-item>
          </template>
        </a-form>
      </div>
    </div>
    <a-modal
      v-model:visible="posi"
      :footer="null"
      :maskClosable="false"
      :closable="false"
      wrapClassName="code-modal"
      forceRender
      :keyboard="false"
      :style="{ top: '29.3rem' }"
    >
      <div class="verify-container flex flex-col align-center">
        <img src="@/assets/images/award/close.svg" class="close-icon" @click="handleCloseModal" />
        <div class="title">Check your email</div>
        <div class="desc">Enter the 6-digital code sent to</div>
        <div class="email">{{ form.email }}</div>
        <VerificationCodeInput
          ref="codeInputRef"
          @complete="onCodeComplete"
          @change="onCodeChange"
        />
        <div class="verify-btn" @click="handleVerifyCode">Verify</div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { debounce } from 'lodash-es'
import type { Rule } from 'ant-design-vue/es/form'
import { message } from 'ant-design-vue'
import VerificationCodeInput from './components/VerificationCodeInput.vue'

const formRef = ref(null)
const form = ref({
  email: '123@qq.com',
  firstName: '',
  lastName: '',
  gender: '',
  occupation: '',
  age: '',
  counterOrRegion: '',
  phone: '',
  portfoilo: '',
  // code: '',
  title: '',
  description: '',
  pdfFile: null,
  videoFile: null
})

// 验证码输入组件引用
const codeInputRef = ref()

const isValidEmail = email => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  return emailRegex.test(email)
}
const validEmail = (rule, value) => {
  if (!value) {
    return Promise.reject('Please input the email address')
  }
  if (!isValidEmail(value)) {
    return Promise.reject('Please input a valid email address')
  }
  return Promise.resolve()
}
const validateNumber = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('Please fill in this section.')
  }
  if (!Number.isInteger(value)) {
    return Promise.reject('Please input digits')
  }
  return Promise.resolve()
}

const validatePhone = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('Please enter your phone number.')
  }
  const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/
  if (!phoneRegex.test(value)) {
    return Promise.reject('Please enter a valid phone number.')
  }
  return Promise.resolve()
}

const validateVerificationCode = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('Please enter the verification code.')
  }
  const codeRegex = /^\d{6}$/
  if (!codeRegex.test(value)) {
    return Promise.reject('Please enter a 6-digit verification code.')
  }
  return Promise.resolve()
}
const rulesRef = {
  email: [{ required: true, validator: validEmail }],
  firstName: [
    { required: true, message: 'Please input your first name', trigger: 'blur' }
  ],
  lastName: [{ required: true, message: 'Please input your last name', trigger: 'blur' }]
}

const formKeys = ref([
  {
    label: 'First Name',
    required: true,
    type: 'input',
    key: 'firstName'
  },
  {
    label: 'Last Name',
    required: true,
    type: 'input',
    key: 'lastName'
  },
  {
    label: 'Gender',
    required: true,
    type: 'select',
    key: 'gender'
  },
  {
    label: 'Occupation',
    required: true,
    type: 'input',
    key: 'occupation'
  },
  {
    label: 'Age',
    required: true,
    type: 'input',
    key: 'age'
  },
  {
    label: 'Country/Region and City',
    required: true,
    type: 'input',
    key: 'counterOrRegion'
  },
  {
    label: 'Phone Number',
    required: true,
    type: 'input',
    key: 'phone'
  },
  {
    label: 'Email Address',
    required: true,
    type: 'button',
    key: 'email',
    tips: 'Please use the same email address you registered with AiDA.'
  },
  {
    label: 'Portfoilo Website/Instagram(Optional)',
    required: false,
    type: 'input',
    key: 'portfoilo'
  },
  {
    label: 'Email Verification Code',
    required: true,
    type: 'input',
    key: 'code',
    tips: 'Please enter a 6-digit numerical code.'
  }
])

const posi = ref(true)
const handleSendCode = debounce(async () => {
  try {
    await formRef.value.validateFields(['email'])
    // TODO: 发送验证码的逻辑
    message.success('Verification code sent successfully!')
    posi.value = true
  } catch (error) {
    // 校验失败时，错误消息会自动显示在表单项下方
    // console.log('Validation failed:', error)
  }
}, 300)

// 验证码输入事件处理
const onCodeComplete = (code: string) => {
  console.log('Verification code completed:', code)
  // 可以在这里处理验证码完成逻辑
}

const onCodeChange = (code: string) => {
  console.log('Verification code changed:', code)
  // 可以在这里处理验证码变化逻辑
}

const handleCloseModal = () => {
  posi.value = false
  codeInputRef.value?.reset()
}

const handleVerifyCode = () => {
  const code = codeInputRef.value?.getCode() || ''
  if (code.length !== 6) {
    message.error('Please enter the complete 6-digit verification code')
    return
  }

  // TODO: 验证验证码的逻辑
  console.log('Verification code:', code)
  message.success('Verification successful!')

  // 关闭模态框
  posi.value = false
}
</script>

<style lang="less" scoped>
.full-row {
  width: 100%;
}
.banner {
  height: 54.8rem;
  background: url('@/assets/images/award/apply_bg.png') no-repeat;
  background-size: 100% 100%;
  text-align: center;
  padding: 12rem 21.4rem 0;
  position: relative;
  .slogan {
    color: #585858;
    font-family: 'ArialBold';
    font-weight: 700;
    font-size: 2.8rem;
    margin-bottom: 4rem;
  }
  .title {
    color: #c7342c;
    font-family: 'PoppinsMedium';
    font-weight: 500;
    font-size: 8rem;
  }
  .form-header {
    height: 16.8rem;
    width: calc(100% - 42.8rem);
    left: 21.4rem;
    bottom: 0;
    position: absolute;
    background-color: #fff;
    border-top-left-radius: 0.8rem;
    border-top-right-radius: 0.8rem;
    text-align: left;
    padding: 6rem 6rem 0;
    .form-title {
      color: #232323;
      font-family: 'PoppinsBold';
      font-weight: 600;
      font-size: 3rem;
      margin-bottom: 1rem;
    }
    .desc {
      color: #b10000;
      // font-family: 'Instrument';
      font-family: revert-layer;
      font-weight: 500;
      font-size: 2.4rem;
    }
  }
}
.form-container {
  padding: 0 21.4rem 12rem;
  background-color: #f5f5f5;
  .form-content {
    padding: 4rem 6rem 6rem;
    background-color: #fff;
    .ant-form {
      display: flex;
      flex-wrap: wrap;
      column-gap: 4rem;
      .ant-form-item {
        width: 66.5rem;

        :deep(label) {
          // display: none;
          flex-direction: row-reverse;
          color: #232323;
          &,
          &::before {
            font-family: 'Arial';
            font-weight: 400;
            font-size: 2rem;
          }
        }
        :deep(.ant-input) {
          border: 0.2rem solid #d5d5d5;
          height: 6rem;
          border-radius: 0.8rem;
        }
      }
    }
    .email-box {
      :deep(.ant-input) {
        border: none !important;
        &:focus {
          box-shadow: none;
        }
      }
      .email-wrapper {
        border-radius: 0.8rem;
        border: 0.2rem solid #d5d5d5;
      }
      .code-btn {
        width: 13rem;
        height: 4rem;
        color: #585858;
        font-family: 'Arial';
        font-weight: 400;
        font-size: 1.8rem;
        line-height: 4rem;
        text-align: center;
        cursor: pointer;
        border-left: 0.1rem solid #d5d5d5;
      }
    }
    .tips {
      font-family: 'Arial';
      font-weight: 400;
      font-size: 1.6rem;
      color: #585858;
      margin-top: 1rem;
    }
  }
}
:deep(.ant-form-item-label) {
  padding: 0 0 1rem;
}
.verify-container {
  width: 60rem;
  height: 49.4rem;
  padding: 6rem 8.6rem;
  background-color: #fff;
  position: relative;
  .close-icon {
    position: absolute;
    width: 2.4rem;
    height: 2.4rem;
    top: 2rem;
    right: 2rem;
    cursor: pointer;
  }
  .title {
    color: #232323;
    font-family: 'PoppinsBold';
    font-weight: 600;
    font-size: 3rem;
    line-height: 5rem;
  }
  .desc {
    color: #585858;
    font-family: 'Arial';
    font-weight: 400;
    font-size: 1.6rem;
    line-height: 3.4rem;
    margin-top: 1.4rem;
  }
  .email {
    font-family: 'ArialBold';
    font-weight: 700;
    font-size: 1.6rem;
    line-height: 3rem;
    color: #232323;
  }
  .verify-btn{
    background-color: #232323;
    height: 4.2rem;
    border-radius: 8px;
    line-height: 4.2rem;
    width: 100%;
    color: #fff;
    text-align: center;
    font-family: 'ArialBold';
    font-weight: 700;
    font-size: 1.6rem;
  }
}
</style>
<style lang="less">
.code-modal {
  .ant-modal-content .ant-modal-body {
    padding: 0;
    // width: 60rem;
  }
}
</style>
