<template>
  <div class="auth-wrapper">
    <a-row justify="center" align="middle" class="full-height">
      <a-col :xs="22" :sm="20" :md="20" :lg="16" :xl="14">
        <div class="auth-shell">
          <a-row :gutter="[0, 0]" class="auth-layout">

            <a-col :xs="24" :md="12" class="auth-pane auth-pane-form">
              <div class="pane-inner">
 
                <div class="brand">
                  <div class="brand-mark">
                    <img
                      :src="logoSrc"
                      alt="Logo institucional"
                      class="brand-logo"
                      @error="logoError = true"
                      v-show="!logoError"
                    />
                    <span v-if="logoError" class="brand-initials">UNA</span>
                  </div>

                  <div class="brand-text">
                    <div class="brand-name">Plataforma de Postulantes</div>
                    <div class="brand-sub">Admisión 2026</div>
                  </div>
                </div>

                <div class="auth-header">
                  <a-typography-title :level="3" style="margin: 0">
                    {{ isRegister ? "Crear Cuenta" : "Iniciar Sesión" }}
                  </a-typography-title>

                  <a-typography-text type="secondary">
                    {{
                      isRegister
                        ? "Complete el formulario para registrarse"
                        : "Ingrese sus credenciales para continuar"
                    }}
                  </a-typography-text>
                </div>

                <a-divider class="auth-divider" />

                <a-form
                  ref="formRef"
                  :model="formState"
                  :rules="rules"
                  @finish="handleSubmit"
                  layout="vertical"
                >
                  <!-- DNI -->
                  <a-form-item v-if="isRegister" label="DNI" name="dni">
                    <a-input v-model:value="formState.dni" size="large" placeholder="Ingrese su DNI">
                      <template #prefix><IdcardOutlined /></template>
                    </a-input>
                  </a-form-item>

                  <a-form-item v-if="isRegister" label="Nombre completo" name="name">
                    <a-input
                      v-model:value="formState.name"
                      size="large"
                      placeholder="Ingrese su nombre completo"
                    >
                      <template #prefix><UserOutlined /></template>
                    </a-input>
                  </a-form-item>


                  <a-form-item label="Correo electrónico" name="email">
                    <a-input v-model:value="formState.email" size="large" placeholder="correo@ejemplo.com">
                      <template #prefix><MailOutlined /></template>
                    </a-input>
                  </a-form-item>


                  <a-form-item label="Contraseña" name="password">
                    <a-input-password
                      v-model:value="formState.password"
                      size="large"
                      placeholder="Ingrese su contraseña"
                    >
                      <template #prefix><LockOutlined /></template>
                    </a-input-password>
                  </a-form-item>

                
                  <a-form-item
                    v-if="isRegister"
                    label="Confirmar contraseña"
                    name="password_confirmation"
                  >
                    <a-input-password
                      v-model:value="formState.password_confirmation"
                      size="large"
                      placeholder="Repita su contraseña"
                    >
                      <template #prefix><LockOutlined /></template>
                    </a-input-password>
                  </a-form-item>


                  <a-row
                    v-if="!isRegister"
                    justify="space-between"
                    align="middle"
                    class="form-row"
                  >
                    <a-checkbox v-model:checked="rememberMe">Recordarme</a-checkbox>

                    <a-button
                      type="link"
                      size="small"
                      class="link-muted"
                      @click="handleForgotPassword"
                    >
                      ¿Olvidó su contraseña?
                    </a-button>
                  </a-row>

                  <a-form-item class="submit-wrap">
                    <a-button type="primary" html-type="submit" block size="large" :loading="loading">
                      {{ isRegister ? "Registrarse" : "Iniciar Sesión" }}
                    </a-button>
                  </a-form-item>
                </a-form>

                <div class="bottom-toggle">
                  <a-typography-text type="secondary">
                    {{ isRegister ? "¿Ya tiene una cuenta?" : "¿No tiene una cuenta?" }}
                  </a-typography-text>

                  <a-button type="link" class="toggle-link" @click="toggleMode">
                    {{ isRegister ? "Iniciar sesión" : "Registrarse" }}
                  </a-button>
                </div>
              </div>
            </a-col>

                <a-col :xs="24" :md="12" class="auth-pane auth-pane-info">
                  <div class="pane-inner pane-inner-info">
                    <div class="info-top">
                      <a-tag class="info-tag">Universidad Nacional del Altiplano – Puno</a-tag>

                      <a-typography-title :level="3" style="margin: 8px 0 0">
                        {{ isRegister ? "Registro de Postulante" : "Portal del Postulante" }}
                      </a-typography-title>

                      <a-typography-text type="secondary">
                        {{
                          isRegister
                            ? "Crea tu cuenta para participar en el proceso de admisión y acceder a todos los servicios del portal."
                            : "Ingresa al portal para gestionar tu inscripción, revisar procesos disponibles y rendir un test de referencia."
                        }}
                      </a-typography-text>
                    </div>

                    <div class="info-section">
                      <div class="info-section-title">
                        {{ isRegister ? "Al registrarte podrás" : "Al ingresar podrás" }}
                      </div>

                      <div class="info-list">

                          <div class="info-item">
                          <span class="info-bullet"></span>
                          <span><b>Rendir un test de referencia</b>.</span>
                        </div>
                        <div class="info-item">
                          <span class="info-bullet"></span>
                          <span><b>Ver procesos disponibles</b> según tu modalidad.</span>
                        </div>

    

                        <div class="info-item">
                          <span class="info-bullet"></span>
                          <span><b>Consultar tu estado</b> de inscripción y seguimiento del proceso.</span>
                        </div>

                        <!-- <div class="info-item">
                          <span class="info-bullet"></span>
                          <span><b>Ver tu resultado detallado</b> por cursos.</span>
                        </div> -->

                        <div class="info-item">
                          <span class="info-bullet"></span>
                          <span><b>Revisar comunicados oficiales</b> del proceso de admisión.</span>
                        </div>
                      </div>
                    </div>

                    <div class="info-foot">
                      <a-typography-text type="secondary">
                        Plataforma oficial de admisión • Soporte en horario institucional
                      </a-typography-text>
                    </div>
                  </div>
                </a-col>


          </a-row>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "../../store/postulanteStore";
import { UserOutlined, MailOutlined, LockOutlined, IdcardOutlined } from "@ant-design/icons-vue";
import { notification } from "ant-design-vue";

const router = useRouter();
const authStore = useAuthStore();
const formRef = ref();

const isRegister = ref(false);
const rememberMe = ref(false);
const loading = ref(false);


const logoSrc = "/logotiny.png";
const logoError = ref(false);

const formState = reactive({
  name: "",
  email: "",
  password: "",
  password_confirmation: "",
  dni: "",
});

notification.config({
  placement: "top",
  duration: 3,
  maxCount: 3,
});

watch(isRegister, () => {
  formRef.value?.clearValidate();
});

const rules = computed(() => ({
  dni: [
    { required: isRegister.value, message: "Ingrese su DNI", trigger: "blur" },
    { pattern: /^\d{8}$/, message: "El DNI debe tener 8 dígitos", trigger: "blur" },
  ],
  name: [
    { required: isRegister.value, message: "Ingrese su nombre completo", trigger: "blur" },
    { min: 3, message: "El nombre debe tener al menos 3 caracteres", trigger: "blur" },
  ],
  email: [
    { required: true, message: "Ingrese su correo electrónico", trigger: "blur" },
    { type: "email", message: "Ingrese un correo electrónico válido", trigger: "blur" },
  ],
  password: [
    { required: true, message: "Ingrese su contraseña", trigger: "blur" },
    { min: 6, message: "La contraseña debe tener al menos 6 caracteres", trigger: "blur" },
  ],
  password_confirmation: [
    { required: isRegister.value, message: "Confirme su contraseña", trigger: "blur" },
    {
      validator: (rule, value) => {
        if (!isRegister.value) return Promise.resolve();
        if (!value) return Promise.reject("Confirme su contraseña");
        if (value !== formState.password) return Promise.reject("Las contraseñas no coinciden");
        return Promise.resolve();
      },
      trigger: "blur",
    },
  ],
}));

const showNotification = (type, message, description = "") => {
  notification[type]({ message, description, duration: 3 });
};

const toggleMode = () => {
  isRegister.value = !isRegister.value;
  Object.keys(formState).forEach((key) => (formState[key] = ""));
  formRef.value?.clearValidate();
};

const handleForgotPassword = () => {
  showNotification("info", "Recuperación de contraseña", "Por favor, contacte al administrador del sistema");
};

const handleSubmit = async () => {
  loading.value = true;
  try {
    if (isRegister.value) {
      const result = await authStore.register({ ...formState });
      if (result.success) {
        showNotification("success", "¡Registro exitoso!", "Tu cuenta ha sido creada correctamente");
        toggleMode();
      } else {
        showNotification("error", "Error en registro", result.error);
      }
    } else {
      const result = await authStore.login({
        email: formState.email,
        password: formState.password,
        device_id: rememberMe.value ? localStorage.getItem("device_id") : null,
      });

      if (result.success) {
        showNotification("success", "¡Bienvenido!", `Hola ${authStore.userName || ""}`);
        router.push("/portal-postulante");
      } else {
        showNotification("error", "Error en login", result.error);
      }
    }
  } catch (error) {
    showNotification("error", "Error", error.response?.data?.message || "Ocurrió un error inesperado");
  } finally {
    loading.value = false;
  }
};

const checkExistingAuth = async () => {
  if (authStore.isAuthenticated) {
    const isValid = await authStore.checkAuth();
    if (isValid) router.push("/portal-postulante");
  }
};
checkExistingAuth();
</script>

<style scoped>
.auth-wrapper,
.auth-wrapper * {
  font-family: "Times New Roman", Times, serif;
}

.auth-wrapper {
  min-height: 100vh;
  background: var(--ant-colorBgLayout, #f5f5f5);
  padding: 40px 16px;
}

.full-height {
  min-height: calc(100vh - 80px);
}

.auth-shell {
  border-radius: 20px;
  overflow: hidden;
  background: var(--ant-colorBgContainer, #ffffff);
  border: 1px solid var(--ant-colorBorderSecondary, rgba(0, 0, 0, 0.06));
  box-shadow: var(--ant-boxShadowSecondary, 0 18px 48px rgba(0, 0, 0, 0.14));
}

.auth-layout {
  min-height: 520px;
}

.auth-pane {
  padding: 28px;
}

.auth-pane-form {
  background: var(--ant-colorBgContainer, #ffffff);
}

.auth-pane-info {
  background: var(--ant-colorFillAlter, #fafafa);
  border-left: 1px solid var(--ant-colorBorderSecondary, rgba(0, 0, 0, 0.06));
}

.pane-inner {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.pane-inner-info {
  justify-content: space-between;
}

/* Branding */
.brand {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 6px;
}

.brand-mark {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  background: var(--ant-colorBgElevated, #fff);
  border: 1px solid var(--ant-colorBorderSecondary, rgba(0, 0, 0, 0.06));
  display: grid;
  place-items: center;
  overflow: hidden;
  box-shadow: var(--ant-boxShadowSecondary, 0 10px 24px rgba(0, 0, 0, 0.12));
}

.brand-logo {
  width: 100%;
  height: 100%;
  object-fit: contain;
  padding: 6px;
}

.brand-initials {
  color: var(--ant-colorPrimary, #1677ff);
  font-weight: 800;
  letter-spacing: 0.5px;
}

.brand-name {
  font-weight: 800;
  color: var(--ant-colorTextHeading, #111827);
  line-height: 1.2;
}

.brand-sub {
  color: var(--ant-colorTextSecondary, #6b7280);
  font-weight: 600;
  font-size: 0.95rem;
}

.auth-header {
  text-align: left;
}

.auth-divider {
  margin: 6px 0 14px;
}

:deep(.ant-input-affix-wrapper),
:deep(.ant-input-password),
:deep(.ant-input) {
  border-radius: 12px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 700;
}

.form-row {
  margin-top: 4px;
}

.link-muted {
  padding: 0;
}

.submit-wrap {
  margin-top: 10px;
  margin-bottom: 0;
}

:deep(.ant-btn-primary) {
  border-radius: 12px;
  height: 48px;
  font-weight: 800;
  box-shadow: var(--ant-boxShadowSecondary, 0 12px 28px rgba(0, 0, 0, 0.14));
}

.bottom-toggle {
  margin-top: auto;
  padding-top: 6px;
}

.toggle-link {
  padding: 0;
  font-weight: 800;
}

.info-top {
  text-align: left;
}

.info-tag {
  border: 0;
  background: color-mix(in srgb, var(--ant-colorPrimary) 14%, transparent);
  color: var(--ant-colorPrimary, #1677ff);
  font-weight: 800;
  border-radius: 999px;
  padding: 6px 12px;
}

.info-section {
  margin-top: 8px;
}

.info-section-title {
  font-weight: 800;
  color: var(--ant-colorTextHeading, #111827);
  margin: 6px 0 10px;
}

.info-list {
  margin-top: 10px;
  display: grid;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  color: var(--ant-colorText, #374151);
  font-weight: 600;
  line-height: 1.45;
}

.info-bullet {
  width: 10px;
  height: 10px;
  margin-top: 6px;
  border-radius: 999px;
  background: var(--ant-colorPrimary, #1677ff);
}

.info-foot {
  padding-top: 10px;
  border-top: 1px solid var(--ant-colorBorderSecondary, rgba(0, 0, 0, 0.06));
}

@media (max-width: 768px) {
  .auth-pane {
    padding: 22px;
  }
  .auth-pane-info {
    border-left: none;
    border-top: 1px solid var(--ant-colorBorderSecondary, rgba(0, 0, 0, 0.06));
  }
  .auth-layout {
    min-height: auto;
  }
}

@supports not (color: color-mix(in srgb, white 50%, black)) {
  .info-tag {
    background: rgba(22, 119, 255, 0.12);
  }
}
</style>