<template>
  <div>
    <h1>Bild hochladen</h1>
    <div class="upload-mode-switch">
      <button type="button" :class="{ active: uploadMode === 'single' }" @click="uploadMode = 'single'">
        Einzel-Upload
      </button>
      <button type="button" :class="{ active: uploadMode === 'bulk' }" @click="uploadMode = 'bulk'">
        Bulk-Upload
      </button>
    </div>

    <form v-if="uploadMode === 'single'" @submit.prevent="uploadImage">
      <div>
        <label for="title">Titel</label>
        <input type="text" id="title" v-model="title" />
      </div>
      <div>
        <label for="description">Beschreibung</label>
        <textarea id="description" v-model="description"></textarea>
      </div>
      <div>
        <label for="image">Bild</label>
        <input type="file" id="image" @change="onFileChange" />
      </div>
      <div>
        <label for="page">Seite</label>
        <select id="page" v-model="selectedPage">
          <option value="">Keine Seite</option>
          <option v-for="page in pages" :key="page.value" :value="page.value">{{ page.caption }}</option>
        </select>
      </div>
      <button type="submit">Hochladen</button>
    </form>

    <form v-else @submit.prevent="uploadImagesBulk">
      <h2>Bulk-Upload</h2>
      <div>
        <label for="bulkBaseTitle">Basis-Titel</label>
        <input type="text" id="bulkBaseTitle" v-model="bulkBaseTitle" placeholder="z. B. Gemeindebrief Bild" required />
      </div>
      <div>
        <label for="bulkStartNumber">Startnummer</label>
        <input type="number" id="bulkStartNumber" v-model.number="bulkStartNumber" min="1" />
      </div>
      <div>
        <label for="bulkDescription">Beschreibung</label>
        <textarea id="bulkDescription" v-model="bulkDescription"></textarea>
      </div>
      <div>
        <label for="bulkImages">Bilder</label>
        <input type="file" id="bulkImages" ref="bulkImagesInput" @change="onBulkFilesChange" accept="image/*" multiple />
      </div>
      <div>
        <label for="bulkPage">Seite</label>
        <select id="bulkPage" v-model="bulkSelectedPage">
          <option value="">Keine Seite</option>
          <option v-for="page in pages" :key="`bulk-${page.value}`" :value="page.value">{{ page.caption }}</option>
        </select>
      </div>
      <p v-if="bulkFiles.length > 0">
        {{ bulkFiles.length }} Datei(en) ausgewählt.
        Erste Titel-Vorschau: <strong>{{ bulkBaseTitle || 'Titel' }} {{ bulkStartNumber }}</strong>
      </p>
      <button type="submit" :disabled="bulkFiles.length === 0">Bulk hochladen</button>
    </form>

    <div v-if="images.length">
      <h2>Hochgeladene Bilder</h2>
      <div v-for="image in images" :key="image.id" class="uploaded-image">
        <img :src="`/images/uploads/${image.filename}`" :alt="image.title" width="100" />
        <input type="text" v-model="image.title" @change="updateImage(image)" />
        <textarea v-model="image.description" @change="updateImage(image)"></textarea>
        <p>{{ formatDate(image.uploadDate) }} {{ formatTimeFromDate(image.uploadDate) }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from '../../axios';
import { formatDate, formatTimeFromDate } from '@/utils/strings'

export default {
  name: 'ImageUpload',
  data() {
    return {
      title: '',
      description: '',
      image: null,
      bulkBaseTitle: '',
      bulkStartNumber: 1,
      bulkDescription: '',
      bulkFiles: [],
      bulkSelectedPage: '',
      selectedPage: '',
      uploadMode: 'single',
      pages: [],
      images: []
    };
  },
  methods: {
    formatDate,
    formatTimeFromDate,
    onFileChange(e) {
      this.image = e.target.files[0];
    },
    onBulkFilesChange(e) {
      this.bulkFiles = Array.from(e.target.files || []);
    },
    async uploadImage() {
      const formData = new FormData();
      formData.append('title', this.title);
      formData.append('description', this.description);
      formData.append('image', this.image);
      formData.append('page', this.selectedPage);

      try {
        await axios.post('/image/', formData);
        this.fetchImages();
        this.resetForm();
      } catch (error) {
        console.error('Fehler beim Hochladen des Bildes:', error);
      }
    },
    async fetchImages() {
      try {
        const response = await axios.get('/image');
        this.images = response.data;
      } catch (error) {
        console.error('Fehler beim Abrufen der Bilder:', error);
      }
    },
    async uploadImagesBulk() {
      if (!this.bulkBaseTitle || this.bulkFiles.length === 0) {
        return;
      }
      const formData = new FormData();
      formData.append('baseTitle', this.bulkBaseTitle);
      formData.append('startNumber', this.bulkStartNumber);
      formData.append('description', this.bulkDescription);
      formData.append('page', this.bulkSelectedPage);
      this.bulkFiles.forEach((file) => formData.append('images', file));

      try {
        await axios.post('/image/bulk', formData);
        this.fetchImages();
        this.resetBulkForm();
      } catch (error) {
        console.error('Fehler beim Bulk-Upload der Bilder:', error);
      }
    },
    async fetchPages() {
      try {
        const response = await axios.get('/menu-data');
        const buildRecursive = function (data, prefix = '') {
          return data.flatMap(item => {
            let children = [];
            if (item.submenu && item.submenu.length) {
              children = buildRecursive(item.submenu, prefix + item.name + " -> ");
            }
            return [{ value: item.link, caption: prefix + item.name }, ...children];
          });
        };

        this.pages = buildRecursive(response.data);
      } catch (error) {
        console.error('Fehler beim Abrufen der Seiten:', error);
      }
    },
    async updateImage(image) {
      try {
        await axios.put(`/image/${image.id}`, {
          title: image.title,
          description: image.description
        });
        this.fetchImages();
      } catch (error) {
        console.error('Fehler beim Aktualisieren des Bildes:', error);
      }
    },
    resetForm() {
      this.title = '';
      this.description = '';
      this.image = null;
      this.selectedPage = '';
      document.getElementById('image').value = null;
    },
    resetBulkForm() {
      this.bulkBaseTitle = '';
      this.bulkStartNumber = 1;
      this.bulkDescription = '';
      this.bulkFiles = [];
      this.bulkSelectedPage = '';
      if (this.$refs.bulkImagesInput) {
        this.$refs.bulkImagesInput.value = null;
      }
    }
  },
  mounted() {
    this.fetchImages();
    this.fetchPages();
  }
};
</script>

<style scoped>
form div {
  margin-bottom: 10px;
}

.uploaded-image {
  display: inline-block;
  margin: 0 0 0.5em 0.5em;
  border: 1px solid #e0e0e0;
  padding: 10px;
}

.uploaded-image input,
.uploaded-image textarea {
  width: 100%;
  margin: 5px 0;
}

.upload-mode-switch {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.upload-mode-switch button.active {
  font-weight: bold;
}
</style>