<template>
  <header class="header-container" :class="headerClass">
    <nav class="header-nav">
      <!-- Left side: Hamburger + Brand -->
      <div class="header-left">
        <button
          class="hamburger-btn"
          :class="{ active: menuOpen }"
          @click="$emit('menu-toggle')"
          aria-label="Toggle navigation menu"
        >
          <span class="hamburger-line"></span>
          <span class="hamburger-line"></span>
          <span class="hamburger-line"></span>
        </button>
        <router-link :to="brandLink" class="header-brand">
          <slot name="brand">
            <span>{{ title }}</span>
          </slot>
        </router-link>
      </div>

      <!-- Right side: Server + Period + Company + Theme + User -->
      <div class="header-actions">
        <!-- Server Switch Dropdown or Badge (US-008/US-026) -->
        <template v-if="availableServers && availableServers.length > 1">
          <ServerSelector
            v-model="currentServerId"
            :servers="availableServers"
            variant="header"
            @change="onServerChange"
          />
        </template>
        <div v-else-if="serverName" class="server-badge">
          <i class="pi pi-server"></i>
          <span>{{ serverName }}</span>
        </div>
        <PeriodSelector
          v-if="showPeriod && selectedCompany"
          :period-store="periodStore"
          :companies-store="companiesStore"
          variant="header"
          @period-changed="onPeriodChanged"
        />
        <CompanySelector
          v-if="showCompany"
          :companies-store="companiesStore"
          :show-fiscal-code="true"
          variant="header"
          @company-changed="onCompanyChanged"
        />
        <!-- Theme Toggle Button -->
        <button
          class="theme-toggle-btn"
          @click="cycleTheme"
          :title="themeLabel"
          aria-label="Change theme"
        >
          <i :class="themeIcon"></i>
        </button>
        <!-- User menu slot (only rendered if showUser is true) -->
        <div v-if="showUser">
          <slot name="user-menu">
            <div v-if="currentUser" class="header-user" @click="$emit('user-menu-toggle')">
              <i class="pi pi-user"></i>
              <span class="desktop-only">{{ currentUser?.username || 'User' }}</span>
            </div>
          </slot>
        </div>
      </div>
    </nav>

    <!-- Server Switch Password Modal (US-009) -->
    <Dialog
      v-model:visible="showPasswordModal"
      :header="`Schimbare server: ${targetServerName}`"
      :modal="true"
      :closable="!isSwitching"
      :style="{ width: '320px' }"
      class="server-switch-modal"
    >
      <div class="server-switch-modal-content">
        <div class="form-field">
          <Password
            id="switch-password"
            v-model="switchPassword"
            :feedback="false"
            :toggleMask="true"
            inputClass="w-full"
            class="w-full"
            :disabled="isSwitching"
            @keyup.enter="confirmServerSwitch"
            autofocus
          />
        </div>

        <div v-if="switchError" class="switch-error">
          <i class="pi pi-exclamation-circle"></i>
          <span>{{ switchError }}</span>
        </div>
      </div>

      <template #footer>
        <Button
          label="Anulează"
          severity="secondary"
          :disabled="isSwitching"
          @click="cancelServerSwitch"
        />
        <Button
          label="Confirma"
          :loading="isSwitching"
          :disabled="!switchPassword"
          @click="confirmServerSwitch"
        />
      </template>
    </Dialog>
  </header>
</template>

<script>
import { computed, ref, onMounted, watch } from "vue";
import CompanySelector from "../CompanySelector.vue";
import PeriodSelector from "../PeriodSelector.vue";
import ServerSelector from "../ServerSelector.vue";
import Dialog from "primevue/dialog";
import Password from "primevue/password";
import Button from "primevue/button";

export default {
  name: "AppHeader",
  components: {
    CompanySelector,
    PeriodSelector,
    ServerSelector,
    Dialog,
    Password,
    Button,
  },
  props: {
    // Header title/brand text
    title: {
      type: String,
      default: "ROA2WEB",
    },
    // Router link for brand click
    brandLink: {
      type: String,
      default: "/",
    },
    // Additional CSS class for header (e.g., 'header-container--gradient')
    headerClass: {
      type: String,
      default: "",
    },
    // Is hamburger menu open?
    menuOpen: {
      type: Boolean,
      default: false,
    },
    // Companies store instance (required for selectors)
    companiesStore: {
      type: Object,
      required: true,
    },
    // Period store instance (required for period selector)
    periodStore: {
      type: Object,
      required: true,
    },
    // Current user object for display
    currentUser: {
      type: Object,
      default: null,
    },
    // Show/hide period selector
    showPeriod: {
      type: Boolean,
      default: true,
    },
    // Show/hide company selector
    showCompany: {
      type: Boolean,
      default: true,
    },
    // Show/hide user info
    showUser: {
      type: Boolean,
      default: true,
    },
    // Server name to display (US-026)
    serverName: {
      type: String,
      default: null,
    },
    // Available servers for dropdown (US-008)
    availableServers: {
      type: Array,
      default: () => [],
    },
    // Current server ID for dropdown selection (US-008)
    currentServerIdProp: {
      type: String,
      default: null,
    },
    // Auth store instance for server switch (US-009)
    authStore: {
      type: Object,
      default: null,
    },
  },
  emits: ["menu-toggle", "company-changed", "period-changed", "user-menu-toggle", "server-switch-request", "server-switched"],
  setup(props, { emit }) {
    const selectedCompany = computed(() => props.companiesStore.selectedCompany);

    // Server switch logic (US-008)
    const currentServerId = ref(props.currentServerIdProp);

    // Watch for external changes to currentServerIdProp
    watch(() => props.currentServerIdProp, (newVal) => {
      currentServerId.value = newVal;
    });

    const getServerName = (serverId) => {
      const server = props.availableServers?.find(s => s.id === serverId);
      return server?.name || serverId;
    };

    // Password confirmation modal state (US-009)
    const showPasswordModal = ref(false);
    const switchPassword = ref("");
    const targetServerId = ref(null);
    const targetServerName = ref("");
    const isSwitching = ref(false);
    const switchError = ref("");

    const onServerChange = (event) => {
      const newServerId = event.value;
      // Don't process if same server selected
      if (newServerId === props.currentServerIdProp) {
        return;
      }

      // Store target server info for modal
      targetServerId.value = newServerId;
      targetServerName.value = getServerName(newServerId);

      // Reset modal state
      switchPassword.value = "";
      switchError.value = "";
      isSwitching.value = false;

      // Revert dropdown to current server (will update after successful switch)
      currentServerId.value = props.currentServerIdProp;

      // Open password modal
      showPasswordModal.value = true;
    };

    const cancelServerSwitch = () => {
      showPasswordModal.value = false;
      switchPassword.value = "";
      switchError.value = "";
      targetServerId.value = null;
      targetServerName.value = "";
    };

    const confirmServerSwitch = async () => {
      if (!switchPassword.value || !targetServerId.value) {
        switchError.value = "Introduceți parola";
        return;
      }

      // Check if authStore is available
      if (!props.authStore?.switchServer) {
        switchError.value = "Eroare: authStore nu este disponibil";
        return;
      }

      isSwitching.value = true;
      switchError.value = "";

      try {
        const result = await props.authStore.switchServer(targetServerId.value, switchPassword.value);

        if (result.success) {
          // Close modal
          showPasswordModal.value = false;
          switchPassword.value = "";

          // Update local state to reflect new server
          currentServerId.value = targetServerId.value;

          // Emit event for parent to reload data (companies, periods)
          emit("server-switched", targetServerId.value);
        } else {
          // Show error in modal
          switchError.value = result.error || "Autentificare eșuată";
        }
      } catch (err) {
        switchError.value = err.message || "Eroare la schimbarea serverului";
      } finally {
        isSwitching.value = false;
      }
    };

    const onCompanyChanged = (company) => {
      emit("company-changed", company);
    };

    const onPeriodChanged = (period) => {
      emit("period-changed", period);
    };

    // Theme toggle logic
    const currentTheme = ref(localStorage.getItem('user-theme') || 'auto');

    const themeIcon = computed(() => ({
      'auto': 'pi pi-desktop',
      'light': 'pi pi-sun',
      'dark': 'pi pi-moon'
    }[currentTheme.value]));

    const themeLabel = computed(() => ({
      'auto': 'Tema: Auto (sistem)',
      'light': 'Tema: Light',
      'dark': 'Tema: Dark'
    }[currentTheme.value]));

    const applyTheme = (theme) => {
      if (theme === 'auto') {
        document.documentElement.removeAttribute('data-theme');
        localStorage.removeItem('user-theme');
      } else {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('user-theme', theme);
      }
    };

    const cycleTheme = () => {
      const themes = ['auto', 'light', 'dark'];
      const idx = themes.indexOf(currentTheme.value);
      const next = themes[(idx + 1) % 3];
      currentTheme.value = next;
      applyTheme(next);
    };

    // Initialize theme on mount
    onMounted(() => {
      if (currentTheme.value !== 'auto') {
        applyTheme(currentTheme.value);
      }
    });

    return {
      selectedCompany,
      onCompanyChanged,
      onPeriodChanged,
      currentTheme,
      themeIcon,
      themeLabel,
      cycleTheme,
      // Server switch (US-008)
      currentServerId,
      getServerName,
      onServerChange,
      // Password modal (US-009)
      showPasswordModal,
      switchPassword,
      targetServerId,
      targetServerName,
      isSwitching,
      switchError,
      cancelServerSwitch,
      confirmServerSwitch,
    };
  },
};
</script>
