<template>
    <div class="login-wrapper">
      <Card class="login-card">
        <template #content>
          <div class="login-header">
            <h1 class="login-title">{{ appTitle }}</h1>
          </div>
          <!-- Loading state while detecting auth mode -->
          <div v-if="authStore.loginStep === 'loading'" class="login-loading">
            <i class="pi pi-spin pi-spinner text-4xl text-primary"></i>
            <p>Se încarcă...</p>
          </div>

          <!-- 2FA Step — verificare cod -->
          <div v-else-if="authStore.loginStep === '2fa'" class="login-2fa">
            <div class="twofa-header">
              <p class="twofa-info">
                Cod trimis la <strong>{{ authStore.otpMaskedEmail }}</strong>
              </p>
              <p class="twofa-subinfo">Introduceți codul email sau un cod de recuperare</p>
            </div>

            <div class="form-group">
              <InputText
                id="otp-code"
                v-model="unifiedCode"
                :inputmode="isBackupCodeMode ? 'text' : 'numeric'"
                :placeholder="isBackupCodeMode ? 'Cod de recuperare' : '_ _ _ _ _ _'"
                maxlength="8"
                class="w-full otp-input"
                :class="{ invalid: otpError, 'backup-code-mode': isBackupCodeMode }"
                autocomplete="one-time-code"
                @input="handleUnifiedInput"
                @keyup.enter="handleVerifyUnified"
              />
              <span v-if="otpError" class="form-error">{{ otpError }}</span>
            </div>

            <!-- Eroare din store -->
            <div v-if="authStore.error" class="login-error-message">
              <i class="pi pi-exclamation-triangle"></i>
              <span>{{ authStore.error }}</span>
            </div>

            <!-- Buton verificare -->
            <Button
              label="Verifică"
              class="w-full login-button"
              :loading="authStore.is2FALoading"
              :disabled="unifiedCode.length < 6 || authStore.is2FALoading"
              icon="pi pi-check"
              icon-pos="right"
              @click="handleVerifyUnified"
            />

            <!-- Checkbox "Ține minte dispozitivul" -->
            <div class="twofa-trust-device">
              <Checkbox v-model="trustDevice" inputId="trust-device" :binary="true" />
              <label for="trust-device" class="trust-device-label">
                Ține minte acest dispozitiv 30 de zile
              </label>
            </div>

            <!-- Retrimite codul (doar în modul OTP) -->
            <div v-if="!isBackupCodeMode" class="twofa-resend">
              <span v-if="authStore.resendCountdown > 0" class="resend-countdown">
                Retrimite codul în {{ authStore.resendCountdown }}s
              </span>
              <a
                v-else
                href="#"
                class="resend-link"
                @click.prevent="handleResendOTP"
              >
                Retrimite codul
              </a>
            </div>

            <!-- Înapoi la login -->
            <div class="twofa-back">
              <a href="#" class="back-link" @click.prevent="handleBackFromOTP">
                <i class="pi pi-arrow-left"></i> Înapoi la login
              </a>
            </div>
          </div>

          <!-- Login Form (username + parolă) -->
          <form
            v-else
            class="login-form"
            @submit.prevent="handleLogin"
          >
            <!-- 1. USERNAME -->
            <div class="form-group">
              <label for="identity" class="form-label required">Utilizator</label>
              <InputText
                id="identity"
                v-model="identity"
                type="text"
                placeholder="Introduceți utilizatorul"
                :class="{ invalid: identityError }"
                class="w-full"
                autocomplete="username"
                @blur="handleIdentityBlur"
                @input="handleIdentityInput"
              />
              <span v-if="identityError" class="form-error">
                {{ identityError }}
              </span>
            </div>

            <!-- 2. PAROLĂ -->
            <div class="form-group">
              <label for="password" class="form-label required">Parolă</label>
              <Password
                id="password"
                v-model="password"
                placeholder="Introduceți parola"
                :class="{ invalid: passwordError }"
                class="w-full"
                :feedback="false"
                toggleMask
                autocomplete="current-password"
                @input="clearPasswordError"
              />
              <span v-if="passwordError" class="form-error">
                {{ passwordError }}
              </span>
            </div>

            <!-- 3. SERVER - Always visible, disabled when no servers loaded -->
            <div v-if="!authStore.isSingleServerMode" class="form-group">
              <label for="server" class="form-label required">Server</label>
              <Dropdown
                id="server"
                v-model="selectedServer"
                :options="authStore.availableServers"
                optionLabel="name"
                optionValue="id"
                placeholder="Selectați serverul"
                class="w-full"
                :class="{ invalid: serverError }"
                :disabled="authStore.availableServers.length === 0"
              />
              <span v-if="serverError" class="form-error">
                {{ serverError }}
              </span>
            </div>

            <!-- Error Message -->
            <div v-if="authStore.error" class="login-error-message">
              <i class="pi pi-exclamation-triangle"></i>
              <span>{{ authStore.error }}</span>
            </div>

            <!-- Submit Button -->
            <Button
              type="submit"
              label="Autentificare"
              class="w-full login-button"
              :loading="authStore.isLoading"
              :disabled="!canSubmit"
              icon="pi pi-sign-in"
              icon-pos="right"
            />
          </form>
        </template>

        <template #footer>
          <div class="login-footer">
            <small class="text-color-secondary">
              ROMFAST © {{ currentYear }}
            </small>
          </div>
        </template>
      </Card>

      <!-- Modal: backup codes generate la primul 2FA -->
      <Dialog
        v-model:visible="showBackupCodesModal"
        header="Coduri de recuperare generate"
        :modal="true"
        :closable="false"
        :style="{ width: '400px' }"
      >
        <div class="backup-codes-modal-content">
          <p class="backup-codes-info">
            <strong>Important:</strong> Salvați aceste coduri în siguranță! Ele se afișează o singură dată.
            Folosiți-le dacă nu primiți codul pe email.
          </p>
          <div class="backup-codes-grid">
            <code v-for="code in backupCodesToShow" :key="code" class="backup-code-item">{{ code }}</code>
          </div>
        </div>
        <template #footer>
          <Button
            label="Am salvat codurile"
            icon="pi pi-check"
            @click="showBackupCodesModal = false; router.push(props.redirectPath)"
          />
          <Button
            label="Copiază toate"
            icon="pi pi-copy"
            severity="secondary"
            @click="copyBackupCodes"
          />
        </template>
      </Dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useToast } from "primevue/usetoast";
import Checkbox from "primevue/checkbox";
import Dialog from "primevue/dialog";
import Dropdown from "primevue/dropdown";
import Password from "primevue/password";

// Props for app-specific customization
const props = defineProps({
  appTitle: {
    type: String,
    required: true,
  },
  appSubtitle: {
    type: String,
    default: '',
  },
  appIcon: {
    type: String,
    default: '',
  },
  redirectPath: {
    type: String,
    default: "/",
  },
  authStore: {
    type: Object,
    required: true,
  },
});

const router = useRouter();
const route = useRoute();
const toast = useToast();

// Form data — login normal
const identity = ref("");
const identityError = ref("");
const selectedServer = ref(null);
const serverError = ref("");
const password = ref("");
const passwordError = ref("");

// Form data — 2FA (unified: acceptă atât cod OTP cât și cod de recuperare)
const unifiedCode = ref("");
const otpError = ref("");
const trustDevice = ref(false);
const backupCodesToShow = ref([]);
const showBackupCodesModal = ref(false);

// true când input-ul conține litere → mod cod de recuperare
const isBackupCodeMode = computed(() => /[A-Z]/.test(unifiedCode.value));

// Internal state for server loading
const isIdentityVerified = ref(false);

// Computed properties
const currentYear = computed(() => new Date().getFullYear());

// Form validation
const canSubmit = computed(() => {
  // Must have username and password
  if (!identity.value.trim() || !password.value) return false;

  // In multi-server mode: need server selected (if servers are loaded)
  if (!props.authStore.isSingleServerMode) {
    // If servers are loaded, one must be selected
    if (props.authStore.availableServers.length > 0 && !selectedServer.value) {
      return false;
    }
  }

  return true;
});

// ============================================================================
// LOGIN FORM HANDLERS
// ============================================================================

const clearPasswordError = () => {
  passwordError.value = "";
  props.authStore.clearError();
};

// Load servers when username field loses focus (multi-server mode only)
const loadServers = async () => {
  const trimmed = identity.value.trim();
  if (!trimmed || trimmed.length < 2) return;

  props.authStore.clearError();

  try {
    const result = await props.authStore.checkIdentity(trimmed);

    if (result.exists) {
      isIdentityVerified.value = true;

      // Auto-select server if only one
      if (props.authStore.availableServers.length === 1) {
        selectedServer.value = props.authStore.availableServers[0].id;
      } else if (props.authStore.selectedServerId) {
        selectedServer.value = props.authStore.selectedServerId;
      }
    } else {
      // Username not found - clear servers
      isIdentityVerified.value = false;
      selectedServer.value = null;
    }
  } catch (error) {
    console.error("Check identity error:", error);
  }
};

// Handle identity blur - load servers in multi-server mode
const handleIdentityBlur = async () => {
  if (props.authStore.isSingleServerMode) return;
  if (isIdentityVerified.value) return;

  await loadServers();
};

// Handle identity input - reset servers when user types
const handleIdentityInput = () => {
  identityError.value = "";
  props.authStore.clearError();

  // Reset server selection when username changes
  if (isIdentityVerified.value) {
    isIdentityVerified.value = false;
    selectedServer.value = null;
    props.authStore.availableServers.splice(0);
  }
};

// Login handler
const handleLogin = async () => {
  // Validate username
  if (!identity.value.trim()) {
    identityError.value = "Utilizatorul este obligatoriu";
    return;
  }

  // Validate password
  if (!password.value) {
    passwordError.value = "Parola este obligatorie";
    return;
  }

  // Validate server selection in multi-server mode
  if (!props.authStore.isSingleServerMode &&
      props.authStore.availableServers.length > 0 &&
      !selectedServer.value) {
    serverError.value = "Selectați un server";
    return;
  }

  identityError.value = "";
  passwordError.value = "";
  serverError.value = "";

  try {
    // Build credentials
    const credentials = {
      username: identity.value.trim(),
      password: password.value,
    };

    // Add server_id for multi-server mode
    if (!props.authStore.isSingleServerMode && selectedServer.value) {
      credentials.server_id = selectedServer.value;
    }

    const result = await props.authStore.login(credentials);

    if (result.success && result.requires_2fa) {
      // Backend cere verificare OTP — focus pe input-ul de cod
      unifiedCode.value = "";
      otpError.value = "";
      setTimeout(() => {
        const otpInput = document.getElementById("otp-code");
        if (otpInput) otpInput.focus();
      }, 100);
      return; // Nu redirectăm — așteptăm codul
    }

    if (result.success) {
      toast.add({
        severity: "success",
        summary: "Autentificare reușită",
        detail: `Bine ați venit, ${props.authStore.user?.full_name || identity.value}!`,
        life: 3000,
      });

      router.push(props.redirectPath);
    } else {
      // Map backend error messages to user-friendly Romanian messages
      const errorMessage = result.error || "Autentificare eșuată";
      let displayMessage = errorMessage;

      if (errorMessage.toLowerCase().includes("password") ||
          errorMessage.toLowerCase().includes("parola") ||
          errorMessage.toLowerCase().includes("invalid credentials") ||
          errorMessage.toLowerCase().includes("incorrect")) {
        displayMessage = "Parolă incorectă";
      } else if (errorMessage.toLowerCase().includes("inactive") ||
                 errorMessage.toLowerCase().includes("inactiv") ||
                 errorMessage.toLowerCase().includes("disabled") ||
                 errorMessage.toLowerCase().includes("blocat")) {
        displayMessage = "Cont inactiv";
      } else if (errorMessage.toLowerCase().includes("not found") ||
                 errorMessage.toLowerCase().includes("user")) {
        displayMessage = "Utilizator negăsit";
      }

      toast.add({
        severity: "error",
        summary: "Autentificare eșuată",
        detail: displayMessage,
        life: 5000,
      });
    }
  } catch (err) {
    console.error("Login error:", err);
    toast.add({
      severity: "error",
      summary: "Eroare",
      detail: "A apărut o eroare la autentificare",
      life: 5000,
    });
  }
};

// ============================================================================
// 2FA HANDLERS
// ============================================================================

// Input unificat: filtrează și limitează lungimea în funcție de mod
const handleUnifiedInput = (event) => {
  otpError.value = "";
  props.authStore.clearError();

  let val = event.target.value.toUpperCase().replace(/[^A-Z0-9]/g, "");
  // OTP: doar cifre → maxim 6; backup code: are litere → maxim 8
  if (/^[0-9]*$/.test(val)) {
    val = val.slice(0, 6);
  } else {
    val = val.slice(0, 8);
  }
  unifiedCode.value = val;
};

// Verificare unificată — detectează tipul codului și apelează handler-ul corect
const handleVerifyUnified = async () => {
  if (unifiedCode.value.length < 6) return;

  otpError.value = "";

  if (isBackupCodeMode.value) {
    // Cod de recuperare (alfanumeric)
    const result = await props.authStore.verifyBackupCode({
      code: unifiedCode.value,
      trustDevice: trustDevice.value,
    });
    if (result.success) {
      toast.add({
        severity: "success",
        summary: "Autentificare reușită",
        detail: "Ați folosit un cod de recuperare",
        life: 3000,
      });
      router.push(props.redirectPath);
    }
  } else {
    // Cod OTP (6 cifre)
    if (unifiedCode.value.length !== 6) {
      otpError.value = "Codul trebuie să aibă exact 6 cifre";
      return;
    }
    const result = await props.authStore.verify2FA({
      code: unifiedCode.value,
      trustDevice: trustDevice.value,
    });
    if (result.success) {
      if (result.backup_codes && result.backup_codes.length > 0) {
        backupCodesToShow.value = result.backup_codes;
        showBackupCodesModal.value = true;
      } else {
        toast.add({
          severity: "success",
          summary: "Autentificare reușită",
          detail: `Bine ați venit, ${props.authStore.user?.username || ""}!`,
          life: 3000,
        });
        router.push(props.redirectPath);
      }
    }
  }
};

// Retrimite cod OTP
const handleResendOTP = async () => {
  const result = await props.authStore.resendOTP();
  if (result.success) {
    toast.add({
      severity: "info",
      summary: "Cod retrimis",
      detail: `Un cod nou a fost trimis la ${props.authStore.otpMaskedEmail}`,
      life: 4000,
    });
  }
};

// Înapoi din 2FA — resetează la formularul de login
const handleBackFromOTP = () => {
  unifiedCode.value = "";
  otpError.value = "";
  trustDevice.value = false;
  props.authStore.clearError();
  props.authStore.resetLoginFlow();
};

// Copiază backup codes în clipboard
const copyBackupCodes = async () => {
  try {
    await navigator.clipboard.writeText(backupCodesToShow.value.join('\n'));
    toast.add({ severity: "success", summary: "Copiat!", life: 2000 });
  } catch (e) {
    toast.add({ severity: "warn", summary: "Nu s-a putut copia automat", life: 2000 });
  }
};

// ============================================================================
// SHARED
// ============================================================================

// Clear errors on mount
const clearErrors = () => {
  props.authStore.clearError();
  identityError.value = "";
  passwordError.value = "";
  serverError.value = "";
  unifiedCode.value = "";
  otpError.value = "";
};

// Watch for selectedServerId changes from store (pre-selection from localStorage)
watch(
  () => props.authStore.selectedServerId,
  (newServerId) => {
    if (newServerId && !selectedServer.value) {
      selectedServer.value = newServerId;
    }
  },
  { immediate: true }
);

// Lifecycle hooks
onMounted(async () => {
  clearErrors();

  // US-005: Check URL query param for server pre-selection
  const preselectedServer = route.query.server;
  if (preselectedServer && !props.authStore.isSingleServerMode) {
    props.authStore.setPreselectedServer(preselectedServer);
  }

  // Detect auth mode and set appropriate login step (US-011)
  await props.authStore.getAuthMode();

  // Focus the right input based on current step
  setTimeout(() => {
    if (props.authStore.loginStep === '2fa') {
      // Restored from session — focus OTP input
      const otpInput = document.getElementById("otp-code");
      if (otpInput) otpInput.focus();
    } else {
      const identityInput = document.getElementById("identity");
      if (identityInput) identityInput.focus();
    }
  }, 100);
});

onUnmounted(() => {
  clearErrors();
});
</script>

<style>
@import "../styles/login.css";

/* Loading state */
.login-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-xl) var(--space-lg);
  gap: var(--space-md);
}

.login-loading p {
  color: var(--text-color-secondary);
  font-size: 0.875rem;
}

/* Server dropdown - use normal styling like other form inputs */
/* No special overrides needed - inherits from primevue-overrides.css */

/* ============================================================
   2FA STEP
   ============================================================ */

.login-2fa {
  padding: 0 var(--space-lg) var(--space-lg);
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
}

.twofa-header {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-sm);
}

.twofa-info {
  color: var(--text-color);
  margin: 0;
  font-size: 0.9375rem;
}

.twofa-subinfo {
  color: var(--text-color-secondary);
  font-size: 0.875rem;
  margin: 0;
}

/* Input OTP — font mare, centrat, cifre spațiate */
.otp-input {
  text-align: center !important;
  font-size: 1.75rem !important;
  letter-spacing: 0.6em !important;
  font-weight: var(--font-semibold) !important;
  font-variant-numeric: tabular-nums;
}

/* Mod cod de recuperare — font monospace, fără spacing exagerat */
.otp-input.backup-code-mode,
.otp-input.backup-code-mode input {
  font-size: 1.375rem !important;
  letter-spacing: 0.05em !important;
  font-family: monospace;
}

.twofa-resend {
  text-align: center;
}

.resend-countdown {
  color: var(--text-color-secondary);
  font-size: 0.875rem;
}

.resend-link {
  color: var(--primary-color);
  cursor: pointer;
  font-size: 0.875rem;
  text-decoration: none;
}

.resend-link:hover {
  text-decoration: underline;
}

.twofa-back {
  text-align: center;
}

.back-link {
  color: var(--text-color-secondary);
  font-size: 0.875rem;
  text-decoration: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: var(--space-xs);
}

.back-link:hover {
  color: var(--text-color);
}

/* Checkbox "Ține minte dispozitivul" */
.twofa-trust-device {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  margin-top: var(--space-xs);
}

.trust-device-label {
  font-size: 0.875rem;
  color: var(--text-color-secondary);
  cursor: pointer;
  user-select: none;
  /* Touch target minim 44px */
  min-height: 44px;
  display: flex;
  align-items: center;
}

/* Backup codes modal */
.backup-codes-modal-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
}

.backup-codes-info {
  color: var(--text-color-secondary);
  font-size: 0.875rem;
  margin: 0;
}

.backup-codes-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--space-sm);
}

.backup-code-item {
  background: var(--surface-ground);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  padding: var(--space-sm) var(--space-md);
  font-family: monospace;
  font-size: 0.9375rem;
  font-weight: var(--font-semibold);
  text-align: center;
  letter-spacing: 0.1em;
}
</style>
