<template>
  <div class="company-selector-mini" ref="dropdownContainer">
    <div class="company-dropdown" ref="dropdown">
      <button
        class="company-trigger"
        @click="toggleDropdown"
        :aria-expanded="dropdownOpen"
        aria-label="Select company"
        title="Alt+Q to quick select"
      >
        <div class="company-info">
          <span class="company-name">{{ selectedCompanyName }}</span>
          <span 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="Search companies..."
              class="search-input"
              @keydown="handleKeyDown"
            />
          </div>
        </div>

        <div class="company-list">
          <div
            v-for="(company, index) in filteredCompanies"
            :key="company.id_firma || company.id"
            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 class="company-sub-info">
                <span class="company-cui">CUI: {{ company.fiscal_code }}</span>
                <span class="company-separator">•</span>
                <span class="company-status" :class="company.status">{{
                  company.status
                }}</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>No companies found</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
import { useCompanyStore } from "../../stores/companies";

export default {
  name: "CompanySelectorMini",
  props: {
    modelValue: {
      type: Object,
      default: null,
    },
  },
  emits: ["update:modelValue", "company-changed"],
  setup(props, { emit }) {
    const companiesStore = useCompanyStore();
    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 || companiesStore.selectedCompany,
      set: (value) => {
        emit("update:modelValue", value);
        companiesStore.setSelectedCompany(value);
      },
    });

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

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

    const filteredCompanies = computed(() => {
      const companies = 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;
        // Focus on search input after dropdown opens
        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 () => {
      // Scroll to selector
      if (dropdownContainer.value) {
        dropdownContainer.value.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
      }

      // Wait for scroll to complete
      await new Promise((resolve) => setTimeout(resolve, 300));

      // Open dropdown and focus
      if (!dropdownOpen.value) {
        dropdownOpen.value = true;
        highlightedIndex.value = -1;
        searchQuery.value = "";
        await nextTick();
        searchInput.value?.focus();
      } else {
        // If already open, just focus
        searchInput.value?.focus();
      }
    };

    const handleGlobalKeyDown = (event) => {
      // Check for Alt+Q (left-hand shortcut)
      if (event.altKey && event.key === "q") {
        event.preventDefault();
        openWithShortcut();
      }
    };

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

    // Watch for search query changes and reset highlighted index
    watch(searchQuery, () => {
      highlightedIndex.value = -1;
    });

    onMounted(() => {
      document.addEventListener("click", handleClickOutside);
      document.addEventListener("keydown", handleGlobalKeyDown);
      // Load companies if not already loaded
      if (companiesStore.companies.length === 0) {
        companiesStore.loadCompanies();
      }
    });

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

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

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

.company-dropdown {
  position: relative;
}

.company-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-sm);
  padding: var(--space-sm) var(--space-md);
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
  width: 100%;
  text-align: left;
  min-width: 300px;
}

.company-trigger:hover {
  border-color: var(--color-primary);
  background: var(--color-bg-secondary);
}

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

.company-name {
  display: block;
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--color-text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

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

.pi-chevron-down {
  transition: transform var(--transition-fast);
  color: var(--color-text-secondary);
  font-size: var(--text-xs);
}

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

.company-dropdown-panel {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-lg);
  z-index: var(--z-dropdown);
  max-height: 300px;
  overflow: hidden;
  opacity: 0;
  transform: translateY(-10px);
  transition: all var(--transition-fast);
}

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

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

.search-wrapper {
  position: relative;
}

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

.search-input {
  width: 100%;
  padding: var(--space-sm) var(--space-sm) var(--space-sm) var(--space-xl);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  background: var(--color-bg);
  color: var(--color-text);
  transition: border-color var(--transition-fast);
}

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

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

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

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

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

.company-item.active {
  background: var(--color-primary);
  color: var(--color-text-inverse);
}

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

.company-item.active.keyboard-highlighted {
  /* When both active and highlighted, outline with semi-transparent white */
  outline: 2px solid rgba(255, 255, 255, 0.5);
}

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

.company-main-name {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  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);
  font-size: var(--text-xs);
  opacity: 0.8;
}

.company-separator {
  opacity: 0.5;
}

.company-status.active {
  color: var(--color-success);
}

.company-status.inactive {
  color: var(--color-error);
}

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

.no-results {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-sm);
  padding: var(--space-xl);
  color: var(--color-text-secondary);
  font-size: var(--text-sm);
}

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

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

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

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

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

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

/* Extra small screens */
@media (max-width: 400px) {
  .company-selector-mini {
    max-width: 160px;
  }

  .company-trigger {
    max-width: 160px;
  }

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

  .company-name {
    max-width: 110px;
  }
}
</style>
