<template>
  <div :class="selectorClass" ref="dropdownContainer">
    <div class="company-dropdown" ref="dropdown">
      <button
        class="company-trigger"
        @click="toggleDropdown"
        :aria-expanded="dropdownOpen"
        aria-label="Selectare firma"
        title="Alt+Q pentru selectare rapida"
      >
        <div class="company-info">
          <span class="company-name">{{ selectedCompanyName }}</span>
          <span v-if="showFiscalCode" class="company-code">{{ selectedCompanyCode }}</span>
        </div>
        <i
          class="pi pi-chevron-down"
          :class="{ 'rotate-180': dropdownOpen }"
        ></i>
      </button>

      <div
        v-show="dropdownOpen"
        class="company-dropdown-panel"
        :class="{ 'panel-open': dropdownOpen }"
      >
        <div class="dropdown-search">
          <div class="search-wrapper">
            <i class="pi pi-search search-icon"></i>
            <input
              ref="searchInput"
              type="text"
              v-model="searchQuery"
              placeholder="Cauta firma..."
              class="search-input"
              @keydown="handleKeyDown"
            />
          </div>
        </div>

        <div class="company-list">
          <div
            v-for="(company, index) in filteredCompanies"
            :key="company.id_firma"
            class="company-item"
            :class="{
              active: company.id_firma === selectedCompany?.id_firma,
              'keyboard-highlighted': isHighlighted(index),
            }"
            @click="selectCompany(company)"
            @mouseenter="highlightedIndex = index"
          >
            <div class="company-details">
              <div class="company-main-name">{{ company.name }}</div>
              <div v-if="showFiscalCode" class="company-sub-info">
                <span class="company-cui">CUI: {{ company.fiscal_code || '-' }}</span>
              </div>
            </div>
            <i
              v-if="company.id_firma === selectedCompany?.id_firma"
              class="pi pi-check company-selected-icon"
            ></i>
          </div>
        </div>

        <div v-if="filteredCompanies.length === 0" class="no-results">
          <i class="pi pi-info-circle"></i>
          <span>Nu s-au gasit firme</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";

export default {
  name: "CompanySelector",
  props: {
    // The companies store instance
    companiesStore: {
      type: Object,
      required: true,
    },
    // Optional v-model binding
    modelValue: {
      type: Object,
      default: null,
    },
    // Show fiscal code in display
    showFiscalCode: {
      type: Boolean,
      default: true,
    },
    // Variant: 'default' (white background) or 'header' (transparent for dark headers)
    variant: {
      type: String,
      default: "default",
      validator: (value) => ['default', 'header'].includes(value),
    },
  },
  emits: ["update:modelValue", "company-changed"],
  setup(props, { emit }) {
    const dropdown = ref(null);
    const dropdownContainer = ref(null);
    const searchInput = ref(null);
    const dropdownOpen = ref(false);
    const searchQuery = ref("");
    const highlightedIndex = ref(-1);

    const selectedCompany = computed({
      get: () => props.modelValue || props.companiesStore.selectedCompany,
      set: (value) => {
        emit("update:modelValue", value);
        props.companiesStore.setSelectedCompany(value);
      },
    });

    const selectedCompanyName = computed(() => {
      return selectedCompany.value?.name || "Selectare firma";
    });

    const selectedCompanyCode = computed(() => {
      return selectedCompany.value?.fiscal_code
        ? `CUI: ${selectedCompany.value.fiscal_code}`
        : "";
    });

    const selectorClass = computed(() => ({
      'company-selector': true,
      'company-selector--header': props.variant === 'header'
    }));

    const filteredCompanies = computed(() => {
      const companies = props.companiesStore.companies || [];
      if (!searchQuery.value || searchQuery.value.trim() === "") {
        return companies;
      }

      const query = searchQuery.value.toLowerCase().trim();
      return companies.filter(
        (company) =>
          company.name?.toLowerCase().includes(query) ||
          company.fiscal_code?.toLowerCase().includes(query)
      );
    });

    const toggleDropdown = async () => {
      dropdownOpen.value = !dropdownOpen.value;
      if (dropdownOpen.value) {
        searchQuery.value = "";
        highlightedIndex.value = -1;
        await nextTick();
        searchInput.value?.focus();
      }
    };

    const closeDropdown = () => {
      dropdownOpen.value = false;
      searchQuery.value = "";
    };

    const selectCompany = (company) => {
      selectedCompany.value = company;
      emit("company-changed", company);
      closeDropdown();
    };

    const scrollToHighlighted = () => {
      nextTick(() => {
        const highlightedElement = document.querySelector(
          ".company-item.keyboard-highlighted"
        );
        if (highlightedElement) {
          highlightedElement.scrollIntoView({
            block: "nearest",
            behavior: "smooth",
          });
        }
      });
    };

    const handleKeyDown = (event) => {
      if (!dropdownOpen.value || filteredCompanies.value.length === 0) return;

      switch (event.key) {
        case "ArrowDown":
          event.preventDefault();
          highlightedIndex.value =
            (highlightedIndex.value + 1) % filteredCompanies.value.length;
          scrollToHighlighted();
          break;

        case "ArrowUp":
          event.preventDefault();
          if (highlightedIndex.value <= 0) {
            highlightedIndex.value = filteredCompanies.value.length - 1;
          } else {
            highlightedIndex.value--;
          }
          scrollToHighlighted();
          break;

        case "Enter":
          event.preventDefault();
          if (
            highlightedIndex.value >= 0 &&
            highlightedIndex.value < filteredCompanies.value.length
          ) {
            selectCompany(filteredCompanies.value[highlightedIndex.value]);
          }
          break;

        case "Escape":
          closeDropdown();
          break;
      }
    };

    const isHighlighted = (index) => {
      return index === highlightedIndex.value;
    };

    const openWithShortcut = async () => {
      if (dropdownContainer.value) {
        dropdownContainer.value.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
      }

      await new Promise((resolve) => setTimeout(resolve, 300));

      if (!dropdownOpen.value) {
        dropdownOpen.value = true;
        highlightedIndex.value = -1;
        searchQuery.value = "";
        await nextTick();
        searchInput.value?.focus();
      } else {
        searchInput.value?.focus();
      }
    };

    const handleGlobalKeyDown = (event) => {
      if (event.altKey && event.key === "q") {
        event.preventDefault();
        openWithShortcut();
      }
    };

    const handleClickOutside = (event) => {
      if (dropdown.value && !dropdown.value.contains(event.target)) {
        closeDropdown();
      }
    };

    watch(searchQuery, () => {
      highlightedIndex.value = -1;
    });

    onMounted(() => {
      document.addEventListener("click", handleClickOutside);
      document.addEventListener("keydown", handleGlobalKeyDown);

      // Load companies if not already loaded
      if (props.companiesStore.companies.length === 0) {
        props.companiesStore.loadCompanies();
      }
    });

    onUnmounted(() => {
      document.removeEventListener("click", handleClickOutside);
      document.removeEventListener("keydown", handleGlobalKeyDown);
    });

    return {
      dropdown,
      dropdownContainer,
      searchInput,
      dropdownOpen,
      searchQuery,
      highlightedIndex,
      selectedCompany,
      selectedCompanyName,
      selectedCompanyCode,
      selectorClass,
      filteredCompanies,
      toggleDropdown,
      closeDropdown,
      selectCompany,
      handleKeyDown,
      isHighlighted,
    };
  },
};
</script>

<style scoped>
.company-selector {
  position: relative;
  max-width: 450px;
}

.company-dropdown {
  position: relative;
}

.company-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-sm, 8px);
  padding: var(--space-sm, 8px) var(--space-md, 12px);
  background: var(--color-bg, #fff);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-md, 6px);
  cursor: pointer;
  transition: all 0.15s ease;
  width: 100%;
  text-align: left;
  min-width: 300px;
}

.company-trigger:hover {
  border-color: var(--color-primary, #2563eb);
  background: var(--color-bg-secondary, #f9fafb);
}

.company-info {
  flex: 1;
  min-width: 0;
}

.company-name {
  display: block;
  font-size: var(--text-sm, 14px);
  font-weight: 500;
  color: var(--color-text, #111827);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.company-code {
  display: block;
  font-size: var(--text-xs, 12px);
  color: var(--color-text-secondary, #6b7280);
  margin-top: 2px;
}

.pi-chevron-down {
  transition: transform 0.15s ease;
  color: var(--color-text-secondary, #6b7280);
  font-size: var(--text-xs, 12px);
}

.rotate-180 {
  transform: rotate(180deg);
}

.company-dropdown-panel {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: var(--color-bg, #fff);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-md, 6px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 300px;
  overflow: hidden;
  opacity: 0;
  transform: translateY(-10px);
  transition: all 0.15s ease;
}

.panel-open {
  opacity: 1;
  transform: translateY(0);
}

.dropdown-search {
  padding: var(--space-sm, 8px);
  border-bottom: 1px solid var(--color-border, #e5e7eb);
}

.search-wrapper {
  position: relative;
}

.search-icon {
  position: absolute;
  left: var(--space-sm, 8px);
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-text-secondary, #6b7280);
  font-size: var(--text-sm, 14px);
  pointer-events: none;
}

.search-input {
  width: 100%;
  padding: var(--space-sm, 8px) var(--space-sm, 8px) var(--space-sm, 8px) var(--space-xl, 32px);
  border: 1px solid var(--color-border, #e5e7eb);
  border-radius: var(--radius-sm, 4px);
  font-size: var(--text-sm, 14px);
  background: var(--color-bg, #fff);
  color: var(--color-text, #111827);
  transition: border-color 0.15s ease;
}

.search-input:focus {
  outline: none;
  border-color: var(--color-primary, #2563eb);
}

.company-list {
  max-height: 200px;
  overflow-y: auto;
}

.company-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-md, 12px);
  cursor: pointer;
  transition: background-color 0.15s ease;
  border-bottom: 1px solid var(--color-border-light, #f3f4f6);
}

.company-item:last-child {
  border-bottom: none;
}

.company-item:hover {
  background: var(--color-bg-secondary, #f9fafb);
}

.company-item.active {
  background: var(--color-primary, #2563eb);
  color: #fff;
}

.company-item.keyboard-highlighted {
  background: var(--color-bg-secondary, #f9fafb);
  outline: 2px solid var(--color-primary, #2563eb);
  outline-offset: -2px;
}

.company-item.active.keyboard-highlighted {
  outline: 2px solid rgba(255, 255, 255, 0.5);
}

.company-details {
  flex: 1;
  min-width: 0;
}

.company-main-name {
  font-size: var(--text-sm, 14px);
  font-weight: 500;
  color: inherit;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 2px;
}

.company-sub-info {
  display: flex;
  align-items: center;
  gap: var(--space-xs, 4px);
  font-size: var(--text-xs, 12px);
  opacity: 0.8;
}

.company-selected-icon {
  color: inherit;
  font-size: var(--text-sm, 14px);
}

.no-results {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-sm, 8px);
  padding: var(--space-xl, 24px);
  color: var(--color-text-secondary, #6b7280);
  font-size: var(--text-sm, 14px);
}

/* Mobile adjustments */
@media (max-width: 768px) {
  .company-selector {
    max-width: 200px;
    width: auto;
  }

  .company-trigger {
    min-width: auto;
    max-width: 200px;
    padding: var(--space-xs, 4px) var(--space-sm, 8px);
  }

  .company-info {
    max-width: 140px;
  }

  .company-name {
    font-size: var(--text-xs, 12px);
    max-width: 140px;
  }

  .company-code {
    font-size: 10px;
  }

  .company-dropdown-panel {
    position: fixed;
    left: 8px;
    right: 8px;
    top: 60px;
    width: auto;
    max-height: 70vh;
  }
}

/* Header variant - transparent background for header integration */
.company-selector--header .company-trigger {
  background: transparent;
  border-color: var(--color-border, rgba(0, 0, 0, 0.2));
}

.company-selector--header .company-trigger:hover {
  background: var(--color-bg-secondary, rgba(0, 0, 0, 0.05));
  border-color: var(--color-primary, #2563eb);
}

.company-selector--header .company-name {
  color: var(--color-text, #111827);
}

.company-selector--header .company-code {
  color: var(--color-text-secondary, #6b7280);
}

.company-selector--header .pi-chevron-down {
  color: var(--color-text-secondary, #6b7280);
}

/* Gradient header variant - white text for dark/gradient headers */
.header-container--gradient .company-selector--header .company-trigger {
  border-color: rgba(255, 255, 255, 0.3);
}

.header-container--gradient .company-selector--header .company-trigger:hover {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.5);
}

.header-container--gradient .company-selector--header .company-name {
  color: white;
}

.header-container--gradient .company-selector--header .company-code {
  color: rgba(255, 255, 255, 0.8);
}

.header-container--gradient .company-selector--header .pi-chevron-down {
  color: rgba(255, 255, 255, 0.8);
}

/* Dropdown panel keeps default styling (white background) */
</style>
