<template>
  <div class="login-container">
    <div class="login-wrapper">
      <Card class="login-card">
        <template #header>
          <div class="login-header">
            <i :class="['pi', appIcon, 'text-primary', 'text-6xl']"></i>
            <h1 class="login-title">{{ appTitle }}</h1>
            <p class="login-subtitle">{{ appSubtitle }}</p>
          </div>
        </template>

        <template #content>
          <!-- 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>

          <!-- Simplified Login Form -->
          <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">
              ROA2WEB © {{ currentYear }} - Toate drepturile rezervate
            </small>
          </div>
        </template>
      </Card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useToast } from "primevue/usetoast";
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,
    required: true,
  },
  appIcon: {
    type: String,
    required: true,
  },
  redirectPath: {
    type: String,
    default: "/",
  },
  authStore: {
    type: Object,
    required: true,
  },
});

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

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

// 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;
});

// Methods

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) {
      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,
    });
  }
};

// Clear errors on mount
const clearErrors = () => {
  props.authStore.clearError();
  identityError.value = "";
  passwordError.value = "";
  serverError.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 identity field after auth mode is detected
  setTimeout(() => {
    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 */
</style>
