<template>
  <el-dialog custom-class="forgot-password-dialog" :visible="visible" width="540px" :close-on-click-modal="false"
    destroy-on-close append-to-body @open="handleOpen" @close="handleClose">
    <div slot="title" class="forgot-dialog-title">
      <div class="title-icon">
        <i class="el-icon-lock"></i>
      </div>
      <div>
        <h3>{{ $t('loginDialog.resetPassword') }}</h3>
        <p>{{ $t('loginDialog.resetPasswordDesc') }}</p>
      </div>
    </div>

    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="forgot-form" autocomplete="off">
      <el-form-item :label="`* ${$t('loginDialog.mobileLabel')}`" prop="username">
        <el-input v-model="form.username" clearable autocomplete="off" :placeholder="$t('loginDialog.enterBoundMobile')"></el-input>
      </el-form-item>

      <el-form-item :label="`* ${$t('loginDialog.newPasswordLabel')}`" prop="password">
        <el-input v-model="form.password" clearable show-password autocomplete="new-password"
          :placeholder="$t('loginDialog.enterNewPassword')"></el-input>
      </el-form-item>

      <el-form-item :label="`* ${$t('loginDialog.verificationCodeLabel')}`" prop="vcode">
        <div class="code-row">
          <el-input v-model="form.vcode" clearable autocomplete="off" :placeholder="$t('loginDialog.enterVerificationCode')"></el-input>
          <el-button class="code-btn" :disabled="isDisabled || isGettingCode" :loading="isGettingCode"
            @click="debouncedGetCode">
            {{ sendCodeText }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer" class="forgot-footer">
      <el-button @click="handleClose">{{ $t('loginDialog.cancel') }}</el-button>
      <el-button class="confirm-btn" type="primary" :loading="submitting" @click="handleSubmit">{{ $t('loginDialog.confirmReset') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPasswordCodeAPI, retrieveCodeAPI } from '@/api/login'

export default {
  name: 'ForgotPasswordDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: this.createEmptyForm(),
      sendCodeText: '',
      isDisabled: false,
      isGettingCode: false,
      submitting: false,
      timeCount: 60,
      timer: null,
      debounceTimer: null
    }
  },
  computed: {
    rules() {
      return {
        username: [
          { required: true, message: this.$t('loginDialog.mobileRequired'), trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: this.$t('loginDialog.mobileInvalid'), trigger: 'blur' }
        ],
        password: [{ required: true, message: this.$t('loginDialog.newPasswordRequired'), trigger: 'blur' }],
        vcode: [{ required: true, message: this.$t('loginDialog.codeRequired'), trigger: 'blur' }]
      }
    }
  },
  watch: {
    '$i18n.locale'() {
      this.resetCodeButtonText()
    }
  },
  created() {
    this.resetCodeButtonText()
  },
  beforeDestroy() {
    this.resetCodeState()
    clearTimeout(this.debounceTimer)
  },
  methods: {
    resetCodeButtonText() {
      if (!this.isDisabled) {
        this.sendCodeText = this.$t('loginDialog.getVerificationCode')
      }
    },
    handleOpen() {
      this.resetForm()
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.resetForm()
    },
    resetForm() {
      this.form = this.createEmptyForm()
      this.submitting = false
      this.resetCodeState()
    },
    createEmptyForm() {
      return {
        username: '',
        password: '',
        vcode: '',
        codeid: ''
      }
    },
    debouncedGetCode() {
      if (this.isDisabled || this.isGettingCode) return

      this.isGettingCode = true
      clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        this.getCode()
      }, 300)
    },
    async getCode() {
      if (!this.form.username || !/^1[3-9]\d{9}$/.test(this.form.username)) {
        this.isGettingCode = false
        this.$message.error(this.$t('loginDialog.mobileInvalid'))
        return
      }

      try {
        const res = await retrieveCodeAPI({
          mobile: this.form.username,
          action_type: 'forgotpassword'
        })

        if (res.status === true) {
          this.form.codeid = res.codeid
          this.startCountdown()
          this.$message.success(this.$t('loginDialog.codeSentCheck'))
          return
        }

        this.$message.error(res.msg || this.$t('loginDialog.codeSendFail'))
      } catch (error) {
        this.$message.error(this.$t('loginDialog.codeSendFail'))
      } finally {
        this.isGettingCode = false
      }
    },
    startCountdown() {
      this.timeCount = 59
      this.isDisabled = true
      this.sendCodeText = this.$t('loginDialog.resendCode', { seconds: this.timeCount })

      clearInterval(this.timer)
      this.timer = setInterval(() => {
        if (this.timeCount > 0) {
          this.timeCount--
          this.sendCodeText = this.$t('loginDialog.resendCode', { seconds: this.timeCount })
          return
        }
        this.resetCodeState()
      }, 1000)
    },
    resetCodeState() {
      this.sendCodeText = this.$t('loginDialog.getVerificationCode')
      clearInterval(this.timer)
      this.timer = null
      this.isDisabled = false
      this.timeCount = 60
    },
    handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (!this.form.codeid) {
          this.$message.error(this.$t('loginDialog.getCodeFirst'))
          return
        }

        this.submitting = true
        try {
          const res = await getPasswordCodeAPI({
            mobile: this.form.username,
            password: this.form.password,
            codeid: this.form.codeid,
            vcode: this.form.vcode,
            action_type: 'forgotpassword'
          })

          if (res.status === true) {
            this.$message.success(this.$t('loginDialog.resetSuccess'))
            this.handleClose()
            return
          }

          this.$message.error(res.msg || this.$t('loginDialog.resetFail'))
        } catch (error) {
          this.$message.error(this.$t('loginDialog.resetFail'))
        } finally {
          this.submitting = false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.forgot-password-dialog {
  border-radius: 30px;
  overflow: hidden;

  .el-dialog__header {
    padding: 40px 44px 20px;
    background: #fff;
    border-bottom: 0;
  }

  .el-dialog__body {
    padding: 10px 44px 8px;
  }

  .el-dialog__footer {
    padding: 12px 44px 36px;
  }

  .el-dialog__headerbtn {
    top: 24px;
    right: 24px;
  }
}

.forgot-dialog-title {
  display: flex;
  align-items: center;
  gap: 14px;

  .title-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 44px;
    height: 44px;
    color: #2f6bff;
    font-size: 20px;
    background: #eaf1ff;
    border-radius: 12px;
  }

  h3 {
    margin: 0;
    color: #1f2d3d;
    font-size: 20px;
    font-weight: 600;
  }

  p {
    margin: 6px 0 0;
    color: #8a94a6;
    font-size: 13px;
  }
}

.forgot-form {
  .el-form-item {
    margin-bottom: 28px;
  }

  .el-form-item__error {
    position: static;
    margin-top: 6px;
    padding-top: 0;
    line-height: 1.4;
  }

  .el-form-item__label {
    padding-bottom: 8px;
    color: #344054;
    font-weight: 500;
    line-height: 1;
  }

  .el-input__inner {
    height: 48px;
    border-color: #c8d3e2;
    border-radius: 14px;
    background: rgba(255, 255, 255, 0.94);
  }
}

.code-row {
  display: flex;
  gap: 10px;

  .el-input {
    flex: 1;
  }

  .code-btn {
    height: 48px;
    padding: 0 18px;
    color: #1d4ed8;
    font-size: 14px;
    font-weight: 600;
    white-space: nowrap;
    cursor: pointer;
    border: 1px solid rgba(37, 99, 235, 0.35);
    border-radius: 14px;
    background: rgba(255, 255, 255, 0.94);
    transition: all 0.2s ease;

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}

.forgot-footer {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .el-button {
    width: 100%;
    height: 52px;
    margin-left: 0;
    border-radius: 999px;
    font-size: 16px;
    font-weight: 700;
  }

  .confirm-btn {
    color: #fff;
    background: #020617;
    border-color: #020617;
    box-shadow: 0 16px 34px rgba(2, 6, 23, 0.22);

    &:hover,
    &:focus {
      color: #fff;
      background: #020617;
      border-color: #020617;
    }
  }
}
</style>
