<template>
  <div class="period-selector-mini" ref="dropdownContainer">
    <div class="period-dropdown" ref="dropdown">
      <button
        class="period-trigger"
        @click="toggleDropdown"
        :disabled="!companyStore.selectedCompany"
        :aria-expanded="dropdownOpen"
        aria-label="Select accounting period"
      >
        <div class="period-info">
          <span class="period-label">Perioada:</span>
          <span class="period-name">{{ selectedPeriodDisplay }}</span>
        </div>
        <i
          class="pi pi-chevron-down"
          :class="{ 'rotate-180': dropdownOpen }"
        ></i>
      </button>

      <div
        v-show="dropdownOpen"
        class="period-dropdown-panel"
        :class="{ 'panel-open': dropdownOpen }"
      >
        <div class="period-list">
          <div
            v-for="(period, index) in periodStore.periods"
            :key="`${period.an}-${period.luna}`"
            class="period-item"
            :class="{
              active: isSelected(period),
              'keyboard-highlighted': isHighlighted(index),
            }"
            @click="selectPeriod(period)"
            @mouseenter="highlightedIndex = index"
          >
            <div class="period-details">
              {{ period.display_name }}
            </div>
            <i v-if="isSelected(period)" class="pi pi-check period-selected-icon"></i>
          </div>
        </div>

        <div v-if="periodStore.periods.length === 0" class="no-results">
          <i class="pi pi-info-circle"></i>
          <span>Nu sunt perioade disponibile</span>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: "PeriodSelectorMini",
  emits: ["period-changed"],
  setup(props, { emit }) {
    const periodStore = useAccountingPeriodStore();
    const companyStore = useCompanyStore();
    const dropdown = ref(null);
    const dropdownContainer = ref(null);
    const dropdownOpen = ref(false);
    const highlightedIndex = ref(-1);

    const selectedPeriodDisplay = computed(() => {
      return periodStore.selectedPeriod?.display_name || "Selectare perioada";
    });

    const isSelected = (period) => {
      if (!periodStore.selectedPeriod) return false;
      return (
        period.an === periodStore.selectedPeriod.an &&
        period.luna === periodStore.selectedPeriod.luna
      );
    };

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

    const toggleDropdown = async () => {
      if (!companyStore.selectedCompany) return;
      dropdownOpen.value = !dropdownOpen.value;
      if (dropdownOpen.value) {
        highlightedIndex.value = -1;
      }
    };

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

    const selectPeriod = (period) => {
      periodStore.setSelectedPeriod(period);
      emit("period-changed", period);
      closeDropdown();
    };

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

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

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

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

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

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

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

    // Watch for company changes - load periods and reset to latest
    watch(
      () => companyStore.selectedCompany,
      async (newCompany) => {
        if (newCompany) {
          await periodStore.loadPeriods(newCompany.id_firma);
        } else {
          periodStore.reset();
        }
      },
      { immediate: true }
    );

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

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

    return {
      periodStore,
      companyStore,
      dropdown,
      dropdownContainer,
      dropdownOpen,
      highlightedIndex,
      selectedPeriodDisplay,
      isSelected,
      isHighlighted,
      toggleDropdown,
      closeDropdown,
      selectPeriod,
    };
  },
};
</script>

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

.period-dropdown {
  position: relative;
}

.period-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: 200px;
}

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

.period-trigger:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.period-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.period-label {
  font-size: var(--text-xs);
  color: var(--color-text-secondary);
}

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

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

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

.period-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);
}

.period-list {
  max-height: 280px;
  overflow-y: auto;
}

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

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

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

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

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

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

.period-details {
  flex: 1;
  font-size: var(--text-sm);
}

.period-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) {
  .period-selector-mini {
    max-width: 140px;
    width: auto;
  }

  .period-trigger {
    min-width: auto;
    padding: var(--space-xs) var(--space-sm);
  }

  .period-info {
    flex-direction: row;
    align-items: center;
    gap: var(--space-xs);
  }

  .period-label {
    display: none;
  }

  .period-name {
    font-size: var(--text-xs);
  }

  .period-dropdown-panel {
    position: fixed;
    left: 8px;
    right: 8px;
    top: 60px;
    width: auto;
    max-height: 70vh;
  }
}
</style>
