<template>
  <div class="predef-activities">
    <h2>{{ $t('predefinedActivities.title') }}</h2>
    <div class="grid">
      <div class="list">
        <div class="toolbar">
          <button @click="startCreate" class="btn-primary">{{ $t('predefinedActivities.new') }}</button>
          <button @click="reload" class="btn-secondary">{{ $t('predefinedActivities.reload') }}</button>
        </div>
        <div class="search-section">
          <input 
            type="text" 
            v-model="searchQuery" 
            @input="onSearchInput"
            :placeholder="$t('predefinedActivities.searchPlaceholder')"
            class="search-input"
          />
          <button v-if="searchQuery" @click="clearSearch" class="btn-clear-search">✕</button>
        </div>
        <div class="scope-filters">
          <button
            type="button"
            class="scope-filter"
            :class="{ active: selectedScope === 'all' }"
            @click="selectedScope = 'all'"
          >
            {{ $t('predefinedActivities.filterAll') }}
          </button>
          <button
            type="button"
            class="scope-filter"
            :class="{ active: selectedScope === 'standard' }"
            @click="selectedScope = 'standard'"
          >
            {{ $t('predefinedActivities.filterStandard') }}
          </button>
          <button
            type="button"
            class="scope-filter"
            :class="{ active: selectedScope === 'custom' }"
            @click="selectedScope = 'custom'"
          >
            {{ $t('predefinedActivities.filterCustom') }}
          </button>
        </div>
        <div>
          <button @click="deduplicate" class="btn-secondary">{{ $t('predefinedActivities.deduplicate') }}</button>
        </div>
        <div class="merge-tools">
            <select v-model="mergeSourceId">
              <option disabled value="">{{ $t('predefinedActivities.selectSource') }}</option>
              <option v-for="a in sortedActivities" :key="'s'+a.id" :value="a.id">{{ formatItem(a) }}</option>
            </select>
            <span>→</span>
            <select v-model="mergeTargetId">
              <option disabled value="">{{ $t('predefinedActivities.selectTarget') }}</option>
              <option v-for="a in sortedActivities" :key="'t'+a.id" :value="a.id">{{ formatItem(a) }}</option>
            </select>
            <button class="btn-secondary" :disabled="!canMerge" @click="mergeSelected">{{ $t('predefinedActivities.merge') }}</button>
          </div>
        <ul class="items">
          <li v-for="a in sortedActivities" :key="a.id" :class="{ active: selectedActivity && selectedActivity.id === a.id }" @click="select(a)">
            <div class="title">
              <strong>{{ a.code ? '[' + a.code + '] ' : '' }}{{ a.name }}</strong>
            </div>
            <div class="meta">
              <span v-if="a.duration">{{ a.duration }} {{ $t('predefinedActivities.min') }}</span>
              <span v-if="a.durationText"> ({{ a.durationText }})</span>
              <span v-if="a.excludeFromStats" class="meta-chip">{{ $t('predefinedActivities.excludeFromStats') }}</span>
            </div>
          </li>
        </ul>
      </div>

      <div class="detail" v-if="editModel">
        <h3>{{ editModel.id ? $t('predefinedActivities.editActivity') : $t('predefinedActivities.newActivity') }}</h3>
        <div class="drawing-button-section">
          <button type="button" class="btn-secondary" @click="showDrawingDialog = true">
            {{ editModel.drawingData ? $t('predefinedActivities.editDrawing') : $t('predefinedActivities.createDrawing') }}
          </button>
        </div>
        <form @submit.prevent="save">
          <label>{{ $t('predefinedActivities.name') }}
            <input type="text" v-model="editModel.name" required />
          </label>
          <label>{{ $t('predefinedActivities.code') }}
            <input type="text" v-model="editModel.code" />
          </label>
          <label>{{ $t('predefinedActivities.duration') }}
            <input type="number" v-model.number="editModel.duration" min="0" />
          </label>
          <label>{{ $t('predefinedActivities.durationText') }}
            <input type="text" v-model="editModel.durationText" :placeholder="$t('predefinedActivities.durationTextPlaceholder')" />
          </label>
          <label class="checkbox-field">
            <input type="checkbox" v-model="editModel.excludeFromStats" />
            <span>{{ $t('predefinedActivities.excludeFromStats') }}</span>
          </label>
          <label>{{ $t('predefinedActivities.description') }}
            <textarea v-model="editModel.description" rows="4" />
          </label>
          <div class="image-section">
            <h4>{{ $t('predefinedActivities.addImage') }}</h4>
            <p class="image-help">{{ $t('predefinedActivities.imageHelp') }}</p>
            
            <label>{{ $t('predefinedActivities.imageLink') }}
              <input type="text" v-model="editModel.imageLink" :placeholder="$t('predefinedActivities.imageLinkPlaceholder')" />
            </label>

            <div class="upload-section">
              <label>{{ $t('predefinedActivities.orUploadImage') }}
                <input type="file" accept="image/*" @change="onFileChange" />
              </label>
              <button class="btn-secondary" :disabled="!selectedFile" @click="uploadImage">
                {{ editModel.id ? $t('predefinedActivities.upload') : $t('predefinedActivities.uploadAfterSave') }}
              </button>
              <p v-if="!editModel.id" class="upload-note">
                {{ $t('predefinedActivities.uploadNote') }}
              </p>
            </div>

            <div class="image-list" v-if="images && images.length">
              <h5>{{ $t('predefinedActivities.uploadedImages') }}</h5>
              <div class="image-grid">
                <div v-for="img in images" :key="img.id" class="image-item">
                  <img :src="imageUrl(img)" alt="Predefined Activity Image" />
                  <button class="btn-small btn-danger" @click="deleteImage(img.id)">{{ $t('predefinedActivities.delete') }}</button>
                </div>
              </div>
            </div>
          </div>

          <div class="actions">
            <button type="submit" class="btn-primary">{{ $t('common.save') }}</button>
            <button type="button" class="btn-secondary" @click="cancel">{{ $t('predefinedActivities.cancel') }}</button>
          </div>
        </form>
      </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)"
    />
    
    <!-- Court Drawing Dialog -->
    <CourtDrawingDialog
        v-model="showDrawingDialog"
        :initial-drawing-data="editModel ? editModel.drawingData : null"
        @ok="handleDrawingDialogOk"
    />
</template>

<script>
import apiClient from '../apiClient.js';
import CourtDrawingDialog from '../components/CourtDrawingDialog.vue';

import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';
import { mapGetters } from 'vuex';
import { debounce } from '../utils/debounce.js';
import { buildInfoConfig, buildConfirmConfig, safeErrorMessage } from '../utils/dialogUtils.js';

const STANDARD_ACTIVITY_NAMES = new Set([
  'Begrüßung',
  'Aktivierung',
  'Aufbauen',
  'Turnier',
  'Abbauen',
  'Abschlussgespräch',
]);

const normalizeStandardActivityFlag = (activity) => ({
  ...(activity || {}),
  excludeFromStats: Boolean(activity?.excludeFromStats ?? activity?.exclude_from_stats) || STANDARD_ACTIVITY_NAMES.has(activity?.name),
});

export default {
  name: 'PredefinedActivities',
  components: {
    CourtDrawingDialog,
        InfoDialog,
        ConfirmDialog},
  data() {
    return {
            // Dialog States
            infoDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info'
            },
            confirmDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
                resolveCallback: null
            },
      activities: [],
      selectedActivity: null,
      editModel: null,
      images: [],
      selectedFile: null,
      selectedDrawingData: null,
      mergeSourceId: '',
      mergeTargetId: '',
      searchQuery: '',
      searchResults: [],
      isSearching: false,
      showDrawingDialog: false,
      selectedScope: 'all',
    };
  },
  computed: {
    isStandardActivity() {
      return (activity) => Boolean(activity?.excludeFromStats) || STANDARD_ACTIVITY_NAMES.has(activity?.name);
    },
    filteredActivities() {
      const activitiesToFilter = this.searchQuery.trim() ? this.searchResults : this.activities;
      if (this.selectedScope === 'standard') {
        return (activitiesToFilter || []).filter((activity) => this.isStandardActivity(activity));
      }
      if (this.selectedScope === 'custom') {
        return (activitiesToFilter || []).filter((activity) => !this.isStandardActivity(activity));
      }
      return activitiesToFilter || [];
    },
    sortedActivities() {
      return [...this.filteredActivities].sort((a, b) => {
        const ac = (a.code || '').toLocaleLowerCase('de-DE');
        const bc = (b.code || '').toLocaleLowerCase('de-DE');
        const aEmpty = ac === '';
        const bEmpty = bc === '';
        if (aEmpty !== bEmpty) return aEmpty ? 1 : -1; // leere Codes nach hinten
        if (ac < bc) return -1; if (ac > bc) return 1;
        const an = (a.name || '').toLocaleLowerCase('de-DE');
        const bn = (b.name || '').toLocaleLowerCase('de-DE');
        if (an < bn) return -1; if (an > bn) return 1;
        return 0;
      });
    },
    canMerge() {
      return this.mergeSourceId && this.mergeTargetId && String(this.mergeSourceId) !== String(this.mergeTargetId);
    }
  },
  methods: {
        // Dialog Helper Methods
        async showInfo(title, message, details = '', type = 'info') {
            this.infoDialog = buildInfoConfig({ title, message, details, type });
        },
        
        async showConfirm(title, message, details = '', type = 'info', options = {}) {
            return new Promise((resolve) => {
                this.confirmDialog = buildConfirmConfig({
                    title,
                    message,
                    details,
                    type,
                    resolveCallback: resolve,
                    ...options,
                });
            });
        },
        
        handleConfirmResult(confirmed) {
            if (this.confirmDialog.resolveCallback) {
                this.confirmDialog.resolveCallback(confirmed);
                this.confirmDialog.resolveCallback = null;
            }
            this.confirmDialog.isOpen = false;
        },
        
        // Suchfunktionen
        async onSearchInput() {
            const query = this.searchQuery.trim();
            
            if (!query || query.length < 2) {
                this.searchResults = [];
                return;
            }
            
            this.isSearching = true;
            try {
                const response = await apiClient.get('/predefined-activities/search/query', {
                    params: { q: query, limit: 50 }
                });
                this.searchResults = (response.data || []).map((activity) => normalizeStandardActivityFlag(activity));
            } catch (error) {
                console.error('Error searching activities:', error);
                this.searchResults = [];
            } finally {
                this.isSearching = false;
            }
        },
        
        clearSearch() {
            this.searchQuery = '';
            this.searchResults = [];
        },
        
    parseDrawingData(value) {
      if (!value) return null;
      if (typeof value === 'object') return value;
      try { return JSON.parse(value); } catch (e) { return null; }
    },
    normalizeActivity(activity, images) {
      const drawingData = this.parseDrawingData(activity && activity.drawingData);
      return { ...normalizeStandardActivityFlag(activity), drawingData };
    },
    async reload() {
      const r = await apiClient.get('/predefined-activities');
      this.activities = (r.data || []).map((activity) => normalizeStandardActivityFlag(activity));
    },
    async select(a) {
      this.selectedActivity = a;
      const r = await apiClient.get(`/predefined-activities/${a.id}`);
      const { images, ...activity } = r.data;
      this.images = images || [];
      // Server-Daten normalisieren und ggf. image-drawingData fallbacken
      let model = this.normalizeActivity(activity, images);
      if (!model.drawingData && images && images.length > 0 && images[0].drawingData) {
        model.drawingData = this.parseDrawingData(images[0].drawingData);
      }
      this.editModel = model;
    },
    async reloadImages() {
      if (this.editModel && this.editModel.id) {
        try {
          const r = await apiClient.get(`/predefined-activities/${this.editModel.id}`);
          const { images } = r.data;
          this.images = images || [];
        } catch (error) {
          console.error('Error reloading images:', error);
        }
      }
    },
    formatItem(a) {
      return `${a.code ? '[' + a.code + '] ' : ''}${a.name}`;
    },
    async mergeSelected() {
      if (!this.canMerge) return;
      const src = this.mergeSourceId; const tgt = this.mergeTargetId;
      const confirmed = await this.showConfirm(
        'Aktivitäten zusammenführen',
        `Eintrag #${src} in #${tgt} zusammenführen?`,
        'Alle Verknüpfungen werden auf das Ziel umgebogen, die Quelle wird gelöscht.',
        'warning'
      );
      if (!confirmed) return;
      await apiClient.post('/predefined-activities/merge', { sourceId: src, targetId: tgt });
      this.mergeSourceId = '';
      this.mergeTargetId = '';
      await this.reload();
    },
    startCreate() {
      this.selectedActivity = null;
      this.images = [];
      this.editModel = {
        name: '',
        code: '',
        description: '',
        duration: null,
        durationText: '',
        excludeFromStats: false,
        imageLink: '',
        drawingData: '',
      };
    },
    cancel() {
      this.editModel = null;
      this.selectedActivity = null;
      this.images = [];
    },
    async save() {
      if (!this.editModel) return;
      
      // Prüfe auf Duplikate nur bei neuen Aktivitäten (nicht bei Updates)
      if (!this.editModel.id && this.editModel.code && this.editModel.code.trim()) {
        const codeToCheck = this.editModel.code.trim().toLowerCase();
        const existing = this.activities.find(a => 
          a.code && a.code.trim().toLowerCase() === codeToCheck
        );
        
        if (existing) {
          const confirmed = await this.showConfirm(
            'Aktivität existiert bereits',
            `Eine Aktivität mit dem Kürzel "${this.editModel.code}" existiert bereits:\n${this.formatItem(existing)}\n\nTrotzdem speichern?`,
            '',
            'warning'
          );
          if (!confirmed) {
            return; // Speichern abbrechen
          }
        }
      }
      
      if (this.editModel.id) {
        const { id, ...payload } = this.editModel;
        if (payload.drawingData && typeof payload.drawingData === 'object') {
          payload.drawingData = payload.drawingData;
        }
        const r = await apiClient.put(`/predefined-activities/${id}`, payload);
        this.editModel = this.normalizeActivity(r.data);
      } else {
        const r = await apiClient.post('/predefined-activities', this.editModel);
        this.editModel = this.normalizeActivity(r.data);
      }
      
      // Nach dem Speichern (sowohl CREATE als auch UPDATE): Bild hochladen falls vorhanden
      if (this.selectedFile) {
        await this.uploadImage();
      } else {
      }
      
      await this.reload();
    },
    async onFileChange(e) {
      const file = e.target.files && e.target.files[0] ? e.target.files[0] : null;
      if (!file) {
        this.selectedFile = null;
        return;
      }
      const maxSize = 5 * 1024 * 1024; // 5 MB
      if (!file.type.startsWith('image/')) {
        await this.showInfo('Ungültige Datei', 'Bitte wählen Sie eine Bilddatei aus.', '', 'warning');
        this.selectedFile = null;
        e.target.value = '';
        return;
      }
      if (file.size > maxSize) {
        await this.showInfo('Datei zu groß', 'Das Bild darf maximal 5 MB groß sein.', '', 'warning');
        this.selectedFile = null;
        e.target.value = '';
        return;
      }
      this.selectedFile = file;
    },
    imageUrl(img) {
      return `/api/predefined-activities/${this.editModel.id}/image/${img.id}`;
    },
    async uploadImage() {
      if (!this.editModel || !this.editModel.id || !this.selectedFile) {
        return;
      }
      
      
      const fd = new FormData();
      fd.append('image', this.selectedFile);
      
      // Füge Zeichnungsdaten hinzu, falls vorhanden
      if (this.selectedDrawingData) {
        fd.append('drawingData', JSON.stringify(this.selectedDrawingData));
      }
      
      // Verwende PUT für Updates, POST für neue Activities
      const isUpdate = this.selectedActivity && this.selectedActivity.id === this.editModel.id;
      const method = isUpdate ? 'put' : 'post';
      
      
      try {
        await apiClient[method](`/predefined-activities/${this.editModel.id}/image`, fd, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        
        // Nach Upload Details neu laden
        await this.select(this.editModel);
        this.selectedFile = null;
        
        // Bildliste explizit aktualisieren
        await this.reloadImages();
      } catch (error) {
        console.error('Upload failed:', error);
        const message = safeErrorMessage(error, 'Bild-Upload fehlgeschlagen.');
        await this.showInfo('Fehler', message, '', 'error');
        throw error;
      }
    },
    async deleteImage(imageId) {
      if (!this.editModel || !this.editModel.id) return;
      const confirmed = await this.showConfirm('Bestätigung', 'Bild wirklich löschen?', '', 'warning');
            if (!confirmed) return;
      try {
        await apiClient.delete(`/predefined-activities/${this.editModel.id}/image/${imageId}`);
        // Nach Löschen Details neu laden
        await this.select(this.editModel);
      } catch (error) {
        console.error('Fehler beim Löschen des Bildes:', error);
        this.showInfo('Fehler', 'Fehler beim Löschen des Bildes', '', 'error');
      }
    },
    async deduplicate() {
      const confirmed = await this.showConfirm('Bestätigung', 'Alle Aktivitäten mit identischem Namen werden zusammengeführt. Fortfahren?', '', 'warning');
            if (!confirmed) return;
      await apiClient.post('/predefined-activities/deduplicate', {});
      await this.reload();
    },
    onDrawingSave(drawingData) {
      if (this.editModel) {
        this.editModel.drawingData = drawingData;
        // Automatisch als Bild-Link setzen, wenn es eine Zeichnung gibt
        if (drawingData && !this.editModel.imageLink) {
          this.editModel.imageLink = drawingData;
        }
      }
      // Nicht automatisch speichern, nur wenn User explizit "Speichern" klickt
    },
    handleDrawingDialogOk(result) {
      if (this.editModel && result) {
        // Übernehme alle Daten vom Dialog
        if (result.drawingData) {
          this.editModel.drawingData = result.drawingData;
        }
        if (result.fields) {
          this.editModel.code = result.fields.code || result.code || '';
          this.editModel.name = result.fields.name || result.name || '';
          this.editModel.description = result.fields.description || result.description || '';
        } else {
          // Fallback falls fields nicht vorhanden
          if (result.code) this.editModel.code = result.code;
          if (result.name) this.editModel.name = result.name;
          if (result.description) this.editModel.description = result.description;
        }
      }
    },
    
    async onDrawingImageUpload(file, drawingData) {
      
      // Setze das File und die Zeichnungsdaten für den Upload
      this.selectedFile = file;
      this.selectedDrawingData = drawingData;
      
      // Upload wird erst beim Speichern durchgeführt
    },
    
    async onImageUploaded() {
      // Bildliste aktualisieren
      if (this.editModel && this.editModel.id) {
        await this.select(this.editModel);
      }
    }
  },
  async mounted() {
    await this.reload();
  }
}
</script>

<style scoped>
.predef-activities {
  display: flex;
  flex-direction: column;
}
.grid {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 1rem;
  height: calc(100vh - 170px);
}
.list {
  background: white;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  padding: 0.5rem;
  overflow: auto;
}
.toolbar {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}
.merge-tools { display: inline-flex; align-items: center; gap: .35rem; margin-left: auto; }
select { max-width: 220px; }
.items {
  list-style: none;
  padding: 0;
  margin: 0;
}
.items li {
  padding: 0.5rem;
  border-radius: var(--border-radius-small);
  cursor: pointer;
}
.items li:hover { background: var(--primary-light);
}
.items li.active { background: var(--primary-light); color: var(--primary-color); }
.meta-chip {
  display: inline-flex;
  align-items: center;
  margin-left: 0.4rem;
  padding: 0.1rem 0.4rem;
  border-radius: 999px;
  background: rgba(41, 110, 78, 0.12);
  color: var(--primary-strong, #296e4e);
  font-size: 0.72rem;
  font-weight: 700;
}
.detail {
  background: white;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  padding: 0.75rem;
  position: sticky;
  top: 0;
  align-self: start;
  max-height: calc(100vh - 170px);
  overflow: auto;
}
label { display: block; margin-bottom: 0.5rem; }
.checkbox-field {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.checkbox-field input[type="checkbox"] {
  width: auto;
}
input[type="text"], input[type="number"], textarea { width: 100%; }
.actions { margin-top: 0.75rem; display: flex; gap: 0.5rem; }
.image-section {
  margin: 1rem 0;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
}

.image-help {
  margin: 0 0 1rem 0;
  color: #666;
  font-size: 0.9rem;
}

.upload-section {
  margin: 1rem 0;
  padding: 1rem;
  background: white;
  border-radius: var(--border-radius-small);
  border: 1px solid #ddd;
}

.upload-note {
  margin: 0.5rem 0 0 0;
  color: #666;
  font-size: 0.85rem;
  font-style: italic;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 1rem;
  margin-top: 0.5rem;
}

.image-item {
  position: relative;
  border: 1px solid #ddd;
  border-radius: var(--border-radius-small);
  overflow: hidden;
  background: white;
}

.image-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  display: block;
}

.image-item button {
  position: absolute;
  top: 0.25rem;
  right: 0.25rem;
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
}

.btn-small {
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
}

.btn-danger {
  background: rgba(200, 74, 56, 0.12);
  color: #8b3327;
  border: 1px solid rgba(200, 74, 56, 0.24);
  border-radius: var(--border-radius-small);
}

.btn-danger:hover {
  background: rgba(200, 74, 56, 0.18);
}

.drawing-button-section {
  margin: 1rem 0;
}

/* Suchfeld Styles */
.search-section {
  position: relative;
  margin: 1rem 0;
}

.scope-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 0.45rem;
  margin: 0 0 1rem;
}

.scope-filter {
  border: 1px solid var(--border-color);
  background: var(--surface-subtle, #f3f7fa);
  color: var(--text-color);
  border-radius: 999px;
  padding: 0.35rem 0.75rem;
}

.scope-filter.active {
  background: rgba(41, 110, 78, 0.12);
  border-color: rgba(41, 110, 78, 0.28);
  color: var(--primary-strong, #296e4e);
  font-weight: 700;
}

.search-input {
  width: 100%;
  padding: 0.75rem 2.5rem 0.75rem 1rem;
  border: 2px solid #ddd;
  border-radius: var(--border-radius);
  font-size: 1rem;
  background: white;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.btn-clear-search {
  position: absolute;
  right: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 50%;
  width: 2rem;
  height: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.btn-clear-search:hover {
  background: #f8f9fa;
  color: #333;
}
</style>
