<template>
  <div class="login-container">
    <div class="row full-height items-center justify-center q-pa-md">
      <div class="col-12 col-lg-10 col-xl-8">
        <div class="row login-card">
          <div class="col-md-6 illustration-container">
            <img
              src="/logo/Asset 3.png?height=400&width=400"
              alt="Login Illustration"
              class="illustration-image"
              @click="$router.push({ name: 'dashboard' })"
            />
          </div>
          <!-- Login form section (left side) -->
          <div class="col-12 col-md-6 login-form-container q-pa-lg">
            <h1 class="text-h4 text-weight-bold q-mb-sm">Đăng Kí</h1>
            <p class="text-grey q-mb-lg">
              Đã có tài khoản?
              <a href="/login" class="text-purple">Đăng Nhập</a>
            </p>

            <!-- <form
              class="q-gutter-y-md"
              autocorrect="off"
              autocapitalize="off"
              autocomplete="off"
              spellcheck="false"
            > -->
            <div>
              <div class="text-subtitle2 q-mb-sm required">Tài Khoản</div>
              <q-input
                v-model="username"
                outlined
                type="text"
                placeholder="username"
                class="login-input"
                :rules="[
                  (val) =>
                    (val && val.length > 0) ||
                    'Email/Tài Khoản không để trống.',
                ]"
              />
            </div>

            <div>
              <div class="text-subtitle2 q-mb-sm required">Số Điện Thoại</div>
              <q-input
                v-model="phone"
                outlined
                type="text"
                placeholder="0978567890"
                :rules="[
                  (val) =>
                    (val && val.length > 0) || 'Số điện thoại không để trống.',
                  (val) => {
                    const phoneRegex = /^(0[3|5|7|8|9])+([0-9]{8})\b/;
                    return (
                      (val && val.length >= 10 && phoneRegex.test(val)) ||
                      'Số điện thoại không hợp lệ.'
                    );
                  },
                ]"
                class="login-input"
              />
            </div>
            <div>
              <div class="text-subtitle2 q-mb-sm">Họ Và Tên</div>
              <q-input
                v-model="fullname"
                outlined
                type="text"
                placeholder="Nguyen Van An"
                class="login-input"
              />
            </div>

            <div>
              <div class="row justify-between items-center q-mb-sm">
                <div class="text-subtitle2 required">Mật Khẩu</div>
              </div>
              <q-input
                v-model="password"
                outlined
                :type="isPwdVisible ? 'text' : 'password'"
                :rules="[
                  (val) =>
                    (val && val.length <= 32 && val.length >= 8) ||
                    'Mật khẩu phải từ 8 - 32 kí tự.',
                ]"
                placeholder="Mật khẩu từ 8 - 32 kí tự."
                class="login-input"
              >
                <template v-slot:append>
                  <q-icon
                    :name="isPwdVisible ? 'visibility' : 'visibility_off'"
                    class="cursor-pointer"
                    @click="isPwdVisible = !isPwdVisible"
                  />
                </template>
              </q-input>
            </div>

            <div>
              <div class="row justify-between items-center q-mb-sm">
                <div class="text-subtitle2 required">Nhập Lại Mật Khẩu</div>
                <!-- <a href="#" class="text-purple text-caption"
                    >Quên Mật Khẩu?</a
                  > -->
              </div>
              <q-input
                v-model="password_confirmation"
                aria-autocomplete="none"
                outlined
                :type="isRePwdVisible ? 'text' : 'password'"
                placeholder="Nhập lại mật khẩu từ 8 - 32 kí tự."
                :rules="[
                  (val) =>
                    (val && val.length <= 32 && val.length >= 8) ||
                    'Mật khẩu phải từ 8 - 32 kí tự.',
                  (val) =>
                    (val && val == password) || 'Mật khẩu nhập lại không khớp.',
                ]"
                class="login-input"
              >
                <template v-slot:append>
                  <q-icon
                    :name="isRePwdVisible ? 'visibility' : 'visibility_off'"
                    class="cursor-pointer"
                    @click="isRePwdVisible = !isRePwdVisible"
                  />
                </template>
              </q-input>
            </div>

            <q-btn
              @click="onSubmit"
              color="purple"
              class="full-width q-py-sm login-btn"
              label="ĐĂNG KÍ"
              unelevated
            />
            <!-- </form> -->
          </div>

          <!-- Illustration section (right side) -->
        </div>
      </div>
    </div>
  </div>
  <q-dialog v-model="dialog" :backdrop-filter="backdropFilter" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">Nhập mã xác minh</div>
        <q-space />
        <!-- <q-btn icon="close" flat round dense v-close-popup @click="resetOtp" /> -->
      </q-card-section>

      <q-card-section>
        <p class="text-body1 q-mb-md">
          Chúng tôi đã gửi một mã gồm 6 chữ số tới số điện thoại của bạn
          <strong>{{ phone }}</strong
          >. Vui lòng nhập mã xác minh bên dưới để xác nhận tài khoản của bạn.
          <br />
        </p>

        <div class="otp-input-container">
          <q-input
            v-for="(digit, index) in otpDigits"
            :key="index"
            v-model="otpDigits[index]"
            class="otp-input"
            outlined
            dense
            maxlength="1"
            @update:model-value="focusNextInput(index)"
            @keydown.delete="handleDelete(index, $event)"
            :ref="
              (el) => {
                if (el) otpInputRefs[index] = el;
              }
            "
            :rules="[(val) => !!val || '*']"
          />
        </div>

        <div class="text-center q-mt-md">
          <p class="text-body2">
            Bạn chưa nhận được mã?
            <q-btn
              flat
              dense
              color="primary"
              label="Resend"
              :disable="resendCountdown > 0"
              @click="resendOtp"
            />
            <span v-if="resendCountdown > 0">({{ resendCountdown }}s)</span>
          </p>
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn flat label="Back" color="grey-7" @click="backToPhone" />
        <q-btn
          label="Verify"
          color="primary"
          :loading="verifyingOtp"
          :disable="!isOtpComplete"
          @click="verifyOtp"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script>
import { defineComponent, nextTick } from 'vue';
import { mapGetters, mapActions } from 'vuex';
export default defineComponent({
  name: 'SignUpPage',
  data() {
    return {
      backdropFilter: 'blur(10px)',
      dialog: false,
      otpDigits: ['', '', '', '', '', ''],
      otpInputRefs: [],
      isSubmitting: false,
      error: null,
      inputRefs: [],
      username: '',
      fullname: '',
      password: '',
      phone: '',
      password_confirmation: '',
      isPwdVisible: false,
      isRePwdVisible: false,
      resendCountdown: 0,
      resendTimer: null,
      otpLength: 6,
      verifyingOtp: false,
    };
  },
  computed: {
    isOtpComplete() {
      return this.otpDigits.every((digit) => digit !== '');
    },
  },
  watch: {
    dialog: {
      handler(newValue) {
        console.log('OTP Dialog Open:', newValue);

        if (!newValue && this.resendTimer) {
          clearInterval(this.resendTimer);
          this.resendCountdown = 0;
          this.resendTimer = null;
          return;
        }
        this.startResendCountdown();
      },
      deep: true,
    },
  },
  methods: {
    ...mapActions({
      signUp: 'userModule/signUp',
      setUser: 'userModule/setUser',
      login: 'userModule/login',
    }),
    async onSubmit() {
      try {
        console.log('signUp attempt with:', this.username, this.password);
        await this.signUp({
          username: this.username,
          fullname: this.fullname,
          password: this.password,
          phone: this.phone,
          password_confirmation: this.password_confirmation,
        });
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: 'Tạo tài khoản thành công',
          color: 'positive',
          multiLine: true,
          position: 'top',
          html: true,
          timeout: 1000,
        });
        setTimeout(() => {
          this.$router.push({ name: 'login' });
        }, 1000);
      } catch (error) {
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: this.$t(`${error.response.data.message}`),
          color: 'negative',
          multiLine: true,
          position: 'top',
          html: true,
          classes: 'notify-error',
          timeout: 1000,
        });
      }
    },
    async handleSubmit() {
      const otpValue = this.otpDigits.join('');

      // Validate OTP is complete
      if (otpValue.length !== this.otpLength) {
        this.error = 'Please enter the complete verification code';
        return;
      }

      this.isSubmitting = true;
      this.error = null;

      try {
        // Emit the submit event with the OTP value
        this.$emit('submit', otpValue);
      } catch (err) {
        this.error = err.message || 'Failed to verify code';
      } finally {
        this.isSubmitting = false;
      }
    },
    handleResendCode() {
      // This would typically trigger a new OTP to be sent
      this.$q.notify({
        message: 'Resend code functionality would be implemented here',
        color: 'info',
      });
    },
    resetForm() {
      this.otpDigits = Array(this.otpLength).fill('');
      this.error = null;
    },
    backToPhone() {
      this.dialog = false;
      this.resetForm();
    },
    handleDelete(index, event) {
      if (this.otpDigits[index] === '' && index > 0) {
        this.otpDigits[index - 1] = '';
        nextTick(() => {
          this.otpInputRefs[index - 1].focus();
        });
      }
    },
    focusNextInput(index) {
      console.log(this.otpInputRefs);

      if (index < 5 && this.otpDigits[index] !== '') {
        nextTick(() => {
          this.otpInputRefs[index + 1].focus();
        });
      }
    },
    async resendOtp() {
      try {
        // Simulate API call to resend OTP
        await new Promise((resolve) => setTimeout(resolve, 1000));

        this.startResendCountdown();

        this.$q.notify({
          message: 'OTP resent successfully',
          color: 'positive',
          icon: 'send',
        });
      } catch (error) {
        this.$q.notify({
          message: 'Failed to resend OTP. Please try again.',
          color: 'negative',
          icon: 'error',
        });
      }
    },

    async verifyOtp() {
      this.verifyingOtp = true;

      try {
        // Simulate API call to verify OTP
        await new Promise((resolve) => setTimeout(resolve, 1500));

        // Close OTP dialog and show success
        this.dialog = false;
        this.successDialogOpen = true;
      } catch (error) {
        this.$q.notify({
          message: 'Invalid OTP. Please try again.',
          color: 'negative',
          icon: 'error',
        });
      } finally {
        this.verifyingOtp = false;
      }
    },
    startResendCountdown() {
      this.resendCountdown = 30;
      this.resendTimer = setInterval(() => {
        this.resendCountdown--;
        if (this.resendCountdown <= 0) {
          clearInterval(this.resendTimer);
        }
      }, 1000);
    },
  },
});
</script>

<style scoped>
.login-container {
  height: 100vh;
  background-color: #0303ef;
  position: relative;
  background-image: url('/landing/z6547001438726_7a5bd095bcf160a078e1e1bffee5073a.jpg');
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  left: 50%;
  transform: translateX(-50%);
}
@media (max-width: 599px) {
  .login-container {
    height: 100vh;
    background-color: #0303ef;
    position: relative;
    background-image: url('/landing/smart_city_2.png');
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    left: 50%;
    transform: translateX(-50%);
  }
}
.login-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.login-form-container {
  background: white;
}

.login-input {
  border-radius: 8px;
}

.login-input :deep(.q-field__control) {
  height: 48px;
}

.login-btn {
  height: 48px;
  border-radius: 8px;
  font-weight: bold;
}

.social-btn {
  height: 42px;
  border-radius: 8px;
}

.illustration-container {
  background-color: #f8f5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.illustration-image {
  max-width: 100%;
  height: auto;
}

.text-purple {
  color: #8e24aa !important;
}

.otp-input-container {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.otp-input {
  width: 48px;
}

/* Make sure input is centered */
.otp-input :deep(.q-field__native) {
  text-align: center;
  font-size: 1.2rem;
  font-weight: bold;
}

@media (max-width: 767px) {
  .illustration-container {
    display: none;
  }
}
</style>
