<template>
  <div class="season-selector">
    <label>
      <span>{{ t('seasonSelector.label') }}</span>
      <div class="season-input-group">
        <select v-model="selectedSeasonId" @change="onSeasonChange" class="season-select" :disabled="loading">
          <option value="">{{ loading ? t('seasonSelector.loading') : t('seasonSelector.selectSeason') }}</option>
          <option v-for="season in seasons" :key="season.id" :value="season.id">
            {{ season.season }}
          </option>
        </select>
        <button @click="showNewSeasonForm = !showNewSeasonForm" class="btn-add-season" :title="t('seasonSelector.addSeason')">
          {{ showNewSeasonForm ? '✕' : '+' }}
        </button>
      </div>
    </label>
    
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-if="showNewSeasonForm" class="new-season-form">
      <label>
        <span>{{ t('seasonSelector.newSeason') }}</span>
        <input 
          type="text" 
          v-model="newSeasonString" 
          :placeholder="t('seasonSelector.placeholder')"
          @keyup.enter="createSeason"
          class="season-input"
        >
      </label>
      <div class="form-actions">
        <button @click="createSeason" :disabled="!isValidSeasonFormat" class="btn-create">
          {{ t('seasonSelector.create') }}
        </button>
        <button @click="cancelNewSeason" class="btn-cancel">
          {{ t('seasonSelector.cancel') }}
        </button>
      </div>
    </div>
  </div>

    
    <!-- Info Dialog -->
    <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
    />
    
    <!-- Confirm Dialog -->
    <ConfirmDialog
        v-model="confirmDialog.isOpen"
        :title="confirmDialog.title"
        :message="confirmDialog.message"
        :details="confirmDialog.details"
        :type="confirmDialog.type"
        @confirm="handleConfirmResult(true)"
        @cancel="handleConfirmResult(false)"
    />
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import i18n from '../i18n';
import apiClient from '../apiClient.js';

import InfoDialog from './InfoDialog.vue';
import ConfirmDialog from './ConfirmDialog.vue';
export default {
  name: 'SeasonSelector',
  components: {
    InfoDialog,
    ConfirmDialog
  },
  props: {
    modelValue: {
      type: [String, Number],
      default: null
    },
    showCurrentSeason: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue', 'season-change'],
  setup(props, { emit }) {
    const store = useStore();
    const t = (key, params) => i18n.global.t(key, params);
    
    // Dialog States
    const infoDialog = ref({
      isOpen: false,
      title: '',
      message: '',
      details: '',
      type: 'info'
    });
    const confirmDialog = ref({
      isOpen: false,
      title: '',
      message: '',
      details: '',
      type: 'info',
      resolveCallback: null
    });
    
    // Reactive data
    const seasons = ref([]);
    const selectedSeasonId = ref(props.modelValue);
    const showNewSeasonForm = ref(false);
    const newSeasonString = ref('');
    const loading = ref(false);
    const error = ref(null);
    
    // Computed
    const isValidSeasonFormat = computed(() => {
      const seasonRegex = /^\d{4}\/\d{4}$/;
      return seasonRegex.test(newSeasonString.value);
    });
    
    // Methods
    const getRunningSeasonId = (seasonEntries) => {
      const seasonsList = Array.isArray(seasonEntries) ? seasonEntries : [];
      if (!seasonsList.length) return null;

      const now = new Date();
      const currentYear = now.getFullYear();
      // Saisonlogik in der App: Hinrunde Juli-Dez, Rueckrunde Jan-Jun
      const startYear = now.getMonth() >= 6 ? currentYear : currentYear - 1;
      const endYear = startYear + 1;
      const expectedLabel = `${startYear}/${endYear}`;

      const exact = seasonsList.find((entry) => String(entry?.season || '').trim() === expectedLabel);
      if (exact?.id != null) {
        return exact.id;
      }

      // Fallback: numerisch passend, falls Label leicht abweicht
      const parsed = seasonsList
        .map((entry) => {
          const match = String(entry?.season || '').match(/^(\d{4})\/(\d{4})$/);
          if (!match) return null;
          return {
            id: entry.id,
            start: Number(match[1]),
            end: Number(match[2])
          };
        })
        .filter(Boolean);
      const numericMatch = parsed.find((entry) => entry.start === startYear && entry.end === endYear);
      if (numericMatch?.id != null) {
        return numericMatch.id;
      }

      return null;
    };

    const loadSeasons = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const response = await apiClient.get('/seasons');
        seasons.value = response.data;
        
        // Wenn showCurrentSeason true ist und keine Saison ausgewählt, wähle die laufende Saison
        if (props.showCurrentSeason && !selectedSeasonId.value && seasons.value.length > 0) {
          const runningSeasonId = getRunningSeasonId(seasons.value);
          const fallbackSeason = seasons.value[0];
          selectedSeasonId.value = runningSeasonId ?? fallbackSeason.id;
          const selectedSeason = seasons.value.find((entry) => entry.id == selectedSeasonId.value) || fallbackSeason;
          emit('update:modelValue', selectedSeasonId.value);
          emit('season-change', selectedSeason);
        }
      } catch (err) {
        console.error('Fehler beim Laden der Saisons:', err);
        error.value = t('seasonSelector.errorLoading');
      } finally {
        loading.value = false;
      }
    };
    
    const onSeasonChange = () => {
      const selectedSeason = seasons.value.find(s => s.id == selectedSeasonId.value);
      emit('update:modelValue', selectedSeasonId.value);
      emit('season-change', selectedSeason);
    };
    
    const createSeason = async () => {
      if (!isValidSeasonFormat.value) return;
      
      try {
        const response = await apiClient.post('/seasons', {
          season: newSeasonString.value
        });
        
        const newSeason = response.data;
        seasons.value.unshift(newSeason); // Am Anfang einfügen (neueste zuerst)
        selectedSeasonId.value = newSeason.id;
        emit('update:modelValue', selectedSeasonId.value);
        emit('season-change', newSeason);
        
        // Formular zurücksetzen
        newSeasonString.value = '';
        showNewSeasonForm.value = false;
      } catch (err) {
        console.error('Fehler beim Erstellen der Saison:', err);
        if (err.response?.data?.error === 'alreadyexists') {
          showInfo(t('seasonSelector.hint'), t('seasonSelector.alreadyExists'), '', 'warning');
        } else {
          showInfo(t('common.error'), t('seasonSelector.errorCreating'), '', 'error');
        }
      }
    };
    
    const cancelNewSeason = () => {
      newSeasonString.value = '';
      showNewSeasonForm.value = false;
    };
    
    // Dialog Helper Methods
    const showInfo = async (title, message, details = '', type = 'info') => {
      infoDialog.value = {
        isOpen: true,
        title,
        message,
        details,
        type
      };
    };
    
    const showConfirm = async (title, message, details = '', type = 'info') => {
      return new Promise((resolve) => {
        confirmDialog.value = {
          isOpen: true,
          title,
          message,
          details,
          type,
          resolveCallback: resolve
        };
      });
    };
    
    const handleConfirmResult = (confirmed) => {
      if (confirmDialog.value.resolveCallback) {
        confirmDialog.value.resolveCallback(confirmed);
        confirmDialog.value.resolveCallback = null;
      }
      confirmDialog.value.isOpen = false;
    };
    
    // Watch for prop changes
    watch(() => props.modelValue, (newValue) => {
      selectedSeasonId.value = newValue;
    });
    
    // Lifecycle
    onMounted(() => {
      loadSeasons();
    });
    
    return {
      t,
      infoDialog,
      confirmDialog,
      showInfo,
      showConfirm,
      handleConfirmResult,
      seasons,
      selectedSeasonId,
      showNewSeasonForm,
      newSeasonString,
      loading,
      error,
      isValidSeasonFormat,
      onSeasonChange,
      createSeason,
      cancelNewSeason
    };
  }
};
</script>

<style scoped>
.season-selector {
  margin-bottom: 1rem;
}

.season-selector label {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.season-selector label span {
  font-weight: 600;
  color: var(--text-color);
}

.season-input-group {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.season-select {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-small);
  font-size: 1rem;
  background: white;
}

.season-select:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px var(--primary-light);
}

.btn-add-season {
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius-small);
  width: 2.5rem;
  height: 2.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-weight: bold;
  transition: var(--transition);
}

.btn-add-season:hover {
  background: var(--primary-dark);
}

.new-season-form {
  background: var(--background-light);
  padding: 1rem;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
  margin-top: 0.5rem;
}

.new-season-form label {
  margin-bottom: 1rem;
}

.season-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-small);
  font-size: 1rem;
}

.season-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px var(--primary-light);
}

.form-actions {
  display: flex;
  gap: 0.5rem;
}

.btn-create {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: var(--border-radius-small);
  cursor: pointer;
  font-weight: 600;
  transition: var(--transition);
}

.btn-create:hover:not(:disabled) {
  background: var(--primary-dark);
}

.btn-create:disabled {
  background: var(--text-muted);
  cursor: not-allowed;
}

.btn-cancel {
  background: var(--background-light);
  color: var(--text-color);
  border: 1px solid var(--border-color);
  padding: 0.5rem 1rem;
  border-radius: var(--border-radius-small);
  cursor: pointer;
  font-weight: 600;
  transition: var(--transition);
}

.btn-cancel:hover {
  background: var(--border-color);
}

.error-message {
  color: #dc3545;
  font-size: 0.875rem;
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: var(--border-radius-small);
}
</style>
