<template>
  <div class="contenthidden">
    <div class="contentscroll">
      <div class="create-npc-view">
        <h1>{{ $t('admin.falukant.createNPC.title') }}</h1>
    
    <div class="form-section">
      <div class="form-group">
        <label>{{ $t('admin.falukant.createNPC.region') }}:</label>
        <div class="region-selection">
          <label>
            <input type="checkbox" v-model="allRegions" @change="onAllRegionsChange" />
            {{ $t('admin.falukant.createNPC.allRegions') }}
          </label>
          <select v-model="selectedRegionIds" multiple :disabled="allRegions" class="form-select" size="10">
            <option v-for="region in regions" :key="region.id" :value="region.id">
              {{ region.name }}
            </option>
          </select>
        </div>
      </div>

      <div class="form-group">
        <label>{{ $t('admin.falukant.createNPC.ageRange') }}:</label>
        <div class="age-range">
          <input type="number" v-model.number="minAge" min="0" max="100" class="form-input" />
          <span>{{ $t('admin.falukant.createNPC.to') }}</span>
          <input type="number" v-model.number="maxAge" min="0" max="100" class="form-input" />
          <span>{{ $t('admin.falukant.createNPC.years') }}</span>
        </div>
      </div>

      <div class="form-group">
        <label>{{ $t('admin.falukant.createNPC.titleRange') }}:</label>
        <div class="title-range">
          <select v-model.number="minTitleId" class="form-select">
            <option v-for="title in titles" :key="title.id" :value="title.id">
              {{ $t(`falukant.titles.male.${title.labelTr}`) }} (ID: {{ title.id }})
            </option>
          </select>
          <span>{{ $t('admin.falukant.createNPC.to') }}</span>
          <select v-model.number="maxTitleId" class="form-select">
            <option v-for="title in titles" :key="title.id" :value="title.id">
              {{ $t(`falukant.titles.male.${title.labelTr}`) }} (ID: {{ title.id }})
            </option>
          </select>
        </div>
      </div>

      <div class="form-group">
        <label>{{ $t('admin.falukant.createNPC.count') }}:</label>
        <input type="number" v-model.number="count" min="1" max="500" class="form-input" />
        <div class="help-text">{{ $t('admin.falukant.createNPC.countHelp') }}</div>
      </div>

      <div class="action-buttons">
        <button @click="createNPCs" :disabled="creating" class="btn btn-primary">
          {{ creating ? $t('admin.falukant.createNPC.creating') : $t('admin.falukant.createNPC.create') }}
        </button>
      </div>

      <!-- Fortschrittsanzeige -->
      <div v-if="creating && jobStatus" class="progress-section">
        <div class="progress-header">
          <h3>{{ $t('admin.falukant.createNPC.progress') }}</h3>
          <span class="progress-percentage">{{ jobStatus.progress }}%</span>
        </div>
        <div class="progress-bar-container">
          <div class="progress-bar" :style="{ width: jobStatus.progress + '%' }"></div>
        </div>
        <div class="progress-details">
          <div>{{ $t('admin.falukant.createNPC.progressDetails', { 
            current: jobStatus.current || 0, 
            total: jobStatus.total || 0 
          }) }}</div>
          <div v-if="jobStatus.estimatedTimeRemaining" class="time-remaining">
            {{ formatTimeRemaining(jobStatus.estimatedTimeRemaining) }}
          </div>
        </div>
      </div>
    </div>

    <!-- Ergebnis-Anzeige -->
    <div v-if="result" class="result-section">
      <h2>{{ $t('admin.falukant.createNPC.result') }}</h2>
      <p>{{ $t('admin.falukant.createNPC.createdCount', { count: result.count }) }}</p>
      <p v-if="result.totalCombinations" class="info-text">
        {{ $t('admin.falukant.createNPC.combinationInfo', { 
          perCombination: result.countPerCombination, 
          combinations: result.totalCombinations,
          total: result.count
        }) }}
      </p>
      <div v-if="result.npcs && result.npcs.length > 0" class="npcs-list">
        <div v-for="npc in result.npcs" :key="npc.id" class="npc-item">
          {{ $t(`falukant.titles.${npc.gender}.${npc.title}`) }} {{ npc.firstName }} {{ npc.lastName }} 
          ({{ $t('admin.falukant.createNPC.age') }}: {{ npc.age }}, {{ $t('admin.falukant.createNPC.region') }}: {{ npc.region }})
        </div>
      </div>
    </div>

    <div v-if="error" class="error-message">
      {{ error }}
    </div>
      </div>
    </div>
  </div>
</template>

<script>
import apiClient from '@/utils/axios.js';

export default {
  name: 'AdminFalukantCreateNPCView',
  data() {
    return {
      regions: [],
      titles: [],
      selectedRegionIds: [],
      allRegions: true,
      minAge: 0,
      maxAge: 100,
      minTitleId: 1,
      maxTitleId: 19,
      count: 1,
      creating: false,
      result: null,
      error: null,
      jobId: null,
      jobStatus: null,
      statusPollInterval: null
    };
  },
  beforeUnmount() {
    if (this.statusPollInterval) {
      clearInterval(this.statusPollInterval);
    }
  },
  async mounted() {
    await this.loadRegions();
    await this.loadTitles();
  },
  methods: {
    async loadRegions() {
      try {
        const response = await apiClient.get('/api/admin/falukant/regions');
        this.regions = response.data || [];
      } catch (error) {
        console.error('Error loading regions:', error);
        this.error = this.$t('admin.falukant.createNPC.errorLoadingRegions');
      }
    },
    async loadTitles() {
      try {
        const response = await apiClient.get('/api/admin/falukant/titles');
        this.titles = response.data || [];
        if (this.titles.length > 0) {
          this.minTitleId = this.titles[0].id;
          this.maxTitleId = this.titles[this.titles.length - 1].id;
        }
      } catch (error) {
        console.error('Error loading titles:', error);
        this.error = this.$t('admin.falukant.createNPC.errorLoadingTitles');
      }
    },
    onAllRegionsChange() {
      if (this.allRegions) {
        this.selectedRegionIds = [];
      }
    },
    async createNPCs() {
      if (this.creating) return;
      
      // Validierung
      if (this.minAge < 0 || this.maxAge < 0 || this.minAge > this.maxAge) {
        this.error = this.$t('admin.falukant.createNPC.invalidAgeRange');
        return;
      }
      
      if (this.minTitleId > this.maxTitleId) {
        this.error = this.$t('admin.falukant.createNPC.invalidTitleRange');
        return;
      }
      
      if (this.count < 1 || this.count > 500) {
        this.error = this.$t('admin.falukant.createNPC.invalidCount');
        return;
      }

      this.creating = true;
      this.error = null;
      this.result = null;
      this.jobStatus = null;
      this.jobId = null;

      try {
        const response = await apiClient.post('/api/admin/falukant/npcs/create', {
          regionIds: this.allRegions ? null : this.selectedRegionIds,
          minAge: this.minAge,
          maxAge: this.maxAge,
          minTitleId: this.minTitleId,
          maxTitleId: this.maxTitleId,
          count: this.count
        });
        
        this.jobId = response.data.jobId;
        this.startStatusPolling();
      } catch (error) {
        console.error('Error creating NPCs:', error);
        this.error = error.response?.data?.error || this.$t('admin.falukant.createNPC.errorCreating');
        this.creating = false;
      }
    },
    startStatusPolling() {
      if (this.statusPollInterval) {
        clearInterval(this.statusPollInterval);
      }
      
      this.statusPollInterval = setInterval(async () => {
        if (!this.jobId) return;
        
        try {
          const response = await apiClient.get(`/api/admin/falukant/npcs/status/${this.jobId}`);
          this.jobStatus = response.data;
          
          if (this.jobStatus.status === 'completed') {
            this.result = this.jobStatus.result;
            this.creating = false;
            clearInterval(this.statusPollInterval);
            this.statusPollInterval = null;
          } else if (this.jobStatus.status === 'error') {
            this.error = this.jobStatus.error || this.$t('admin.falukant.createNPC.errorCreating');
            this.creating = false;
            clearInterval(this.statusPollInterval);
            this.statusPollInterval = null;
          }
        } catch (error) {
          console.error('Error polling status:', error);
          if (error.response?.status === 404) {
            // Job nicht gefunden - möglicherweise abgelaufen
            this.error = this.$t('admin.falukant.createNPC.jobNotFound');
            this.creating = false;
            clearInterval(this.statusPollInterval);
            this.statusPollInterval = null;
          }
        }
      }, 1000); // Poll alle Sekunde
    },
    formatTimeRemaining(ms) {
      if (!ms || ms <= 0) return this.$t('admin.falukant.createNPC.almostDone');
      const seconds = Math.floor(ms / 1000);
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      
      if (minutes > 0) {
        return this.$t('admin.falukant.createNPC.timeRemainingMinutes', { 
          minutes, 
          seconds: remainingSeconds 
        });
      }
      return this.$t('admin.falukant.createNPC.timeRemainingSeconds', { seconds });
    }
  }
};
</script>

<style scoped>
.create-npc-view {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.region-selection {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.region-selection label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
}

.form-select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.form-select[multiple] {
  min-height: 200px;
}

.age-range,
.title-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100px;
}

.action-buttons {
  margin-top: 20px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.btn-primary {
  background-color: #28a745;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #218838;
}

.btn-primary:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.result-section {
  background: #d4edda;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.npcs-list {
  margin-top: 15px;
}

.npc-item {
  padding: 8px;
  background: white;
  margin-bottom: 5px;
  border-radius: 4px;
}

.error-message {
  background: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.help-text {
  font-size: 0.9em;
  color: #666;
  margin-top: 5px;
  font-style: italic;
}

.info-text {
  font-size: 0.9em;
  color: #155724;
  margin-top: 5px;
}

.progress-section {
  background: #e7f3ff;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  border: 1px solid #b3d9ff;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.progress-header h3 {
  margin: 0;
  font-size: 1.2em;
}

.progress-percentage {
  font-size: 1.5em;
  font-weight: bold;
  color: #0066cc;
}

.progress-bar-container {
  width: 100%;
  height: 30px;
  background-color: #e0e0e0;
  border-radius: 15px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #28a745, #20c997);
  transition: width 0.3s ease;
  border-radius: 15px;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  font-size: 0.9em;
  color: #666;
}

.time-remaining {
  font-weight: bold;
  color: #0066cc;
}
</style>
