<template>
  <div :class="selectorClass" ref="dropdownContainer">
    <div class="period-dropdown" ref="dropdown">
      <button
        class="period-trigger"
        @click="toggleDropdown"
        :disabled="!hasSelectedCompany"
        :aria-expanded="dropdownOpen"
        aria-label="Selectare perioada contabila"
      >
        <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 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="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";

export default {
  name: "PeriodSelector",
  props: {
    // The accounting period store instance
    periodStore: {
      type: Object,
      required: true,
    },
    // The company store instance (to check if company is selected)
    companiesStore: {
      type: Object,
      required: true,
    },
    // Variant: 'default' (white background) or 'header' (transparent for dark headers)
    variant: {
      type: String,
      default: "default",
      validator: (value) => ['default', 'header'].includes(value),
    },
  },
  emits: ["period-changed"],
  setup(props, { emit }) {
    const dropdown = ref(null);
    const dropdownContainer = ref(null);
    const dropdownOpen = ref(false);
    const highlightedIndex = ref(-1);

    const hasSelectedCompany = computed(() => {
      return !!props.companiesStore.selectedCompany;
    });

    const periods = computed(() => {
      return props.periodStore.periods || [];
    });

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

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

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

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

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

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

    const selectPeriod = (period) => {
      props.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 || periods.value.length === 0) return;

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

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

        case "Enter":
          event.preventDefault();
          if (
            highlightedIndex.value >= 0 &&
            highlightedIndex.value < periods.value.length
          ) {
            selectPeriod(periods.value[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
    watch(
      () => props.companiesStore.selectedCompany,
      async (newCompany) => {
        if (newCompany) {
          await props.periodStore.loadPeriods(newCompany.id_firma);
        } else {
          props.periodStore.reset();
        }
      },
      { immediate: true }
    );

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

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

    return {
      dropdown,
      dropdownContainer,
      dropdownOpen,
      highlightedIndex,
      hasSelectedCompany,
      periods,
      selectedPeriodDisplay,
      selectorClass,
      isSelected,
      isHighlighted,
      toggleDropdown,
      closeDropdown,
      selectPeriod,
    };
  },
};
</script>

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

.period-dropdown {
  position: relative;
}

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

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

.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, 12px);
  color: var(--color-text-secondary, #6b7280);
}

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

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

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

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

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

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

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

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

.period-item.keyboard-highlighted {
  background: var(--color-bg-secondary, #f9fafb);
  outline: 2px solid var(--color-primary, #2563eb);
  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, 14px);
}

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

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

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

  .period-label {
    display: none;
  }

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

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

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

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

.period-selector--header .period-trigger:disabled {
  border-color: var(--color-border, rgba(0, 0, 0, 0.1));
}

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

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

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

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

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

.header-container--gradient .period-selector--header .period-trigger:disabled {
  border-color: rgba(255, 255, 255, 0.15);
}

.header-container--gradient .period-selector--header .period-label {
  color: rgba(255, 255, 255, 0.7);
}

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

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

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