<template>
  <BaseDialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="title"
    :is-modal="true"
    size="large"
    :closable="true"
    :close-on-overlay="true"
    @close="handleClose"
  >
    <div class="image-viewer-content">
      <div class="image-main" :class="{ 'has-images': hasImages }">
        <button
          v-if="hasImages && images.length > 1"
          class="nav-button nav-button--prev"
          @click="showPreviousImage"
          :title="$t('imageViewer.previousImage')"
        >
          ‹
        </button>

        <div class="image-container">
          <img
            v-if="currentImageUrl"
            :src="currentImageUrl"
            :alt="title"
            class="viewer-image"
            :style="imageStyle"
          />
          <div v-else class="no-image">
            {{ $t('imageViewer.noImageAvailable') }}
          </div>
        </div>

        <button
          v-if="hasImages && images.length > 1"
          class="nav-button nav-button--next"
          @click="showNextImage"
          :title="$t('imageViewer.nextImage')"
        >
          ›
        </button>
      </div>

      <div v-if="showActions && hasImages" class="image-actions">
        <button
          v-if="allowRotate && currentImageId"
          @click="rotate('left')"
          class="action-btn"
          :title="$t('imageViewer.rotateLeft')"
        >
          ↺ {{ $t('imageViewer.rotateLeft') }}
        </button>
        <button
          v-if="allowRotate && currentImageId"
          @click="rotate('right')"
          class="action-btn"
          :title="$t('imageViewer.rotateRight')"
        >
          ↻ {{ $t('imageViewer.rotateRight') }}
        </button>
        <button
          v-if="showSetPrimary && currentImage && !currentImage.isPrimary"
          @click="setPrimary"
          class="action-btn"
          :title="$t('imageViewer.setAsPrimary')"
        >
          ⭐ {{ $t('imageViewer.setAsPrimaryButton') }}
        </button>
        <button
          v-if="showDelete && currentImageId"
          @click="deleteImage"
          class="action-btn action-btn--danger"
          :title="$t('imageViewer.deleteImage')"
        >
          🗑️ {{ $t('imageViewer.delete') }}
        </button>
      </div>

      <div v-if="allowUpload" class="upload-section">
        <div class="upload-actions">
          <input type="file" multiple accept="image/*" @change="handleFileSelect" ref="fileInput" style="display: none;" id="image-upload-file">
          <label for="image-upload-file" class="upload-label">
            📁 {{ $t('imageViewer.selectFiles') }}
          </label>
          <input type="file" multiple accept="image/*" capture="environment" @change="handleFileSelect" ref="cameraInput" style="display: none;" id="image-upload-camera">
          <label for="image-upload-camera" class="upload-label">
            📷 {{ $t('imageViewer.camera') }}
          </label>
        </div>
      </div>

      <div v-if="hasImages" class="thumbnail-strip">
        <div
          v-for="image in images"
          :key="image.id"
          class="thumbnail"
          :class="{
            'thumbnail--active': image.id === currentImageId,
            'thumbnail--primary': image.isPrimary
          }"
          @click="selectImage(image.id)"
        >
          <img :src="image.objectUrl || image.url" :alt="`Bild #${image.id}`" />
          <span v-if="image.isPrimary" class="thumbnail-badge">Primär</span>
        </div>
      </div>

      <div v-if="$slots.default" class="extra-content">
        <slot></slot>
      </div>
    </div>

    <template #footer>
      <slot name="footer">
        <button @click="handleClose" class="btn-secondary">
          Schließen
        </button>
      </slot>
    </template>
  </BaseDialog>
</template>

<script>
import BaseDialog from './BaseDialog.vue';

export default {
  name: 'ImageViewerDialog',
  components: {
    BaseDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: 'Bild'
    },
    images: {
      type: Array,
      default: () => []
    },
    activeImageId: {
      type: [Number, String],
      default: null
    },
    memberId: {
      type: [Number, String],
      default: null
    },
    showActions: {
      type: Boolean,
      default: true
    },
    allowRotate: {
      type: Boolean,
      default: true
    },
    allowZoom: {
      type: Boolean,
      default: false
    },
    showDelete: {
      type: Boolean,
      default: false
    },
    showSetPrimary: {
      type: Boolean,
      default: false
    },
    allowUpload: {
      type: Boolean,
      default: false
    },
    imageUrl: {
      type: String,
      default: ''
    }
  },
  emits: [
    'update:modelValue',
    'update:activeImageId',
    'close',
    'rotate',
    'delete-image',
    'set-primary',
    'upload-images'
  ],
  data() {
    return {
      scale: 1,
      currentImageId: this.activeImageId
    };
  },
  computed: {
    hasImages() {
      return Array.isArray(this.images) && this.images.length > 0;
    },
    currentImage() {
      if (!this.hasImages) {
        return null;
      }
      const match = this.images.find(img => img.id === this.currentImageId);
      return match || this.images[0] || null;
    },
    currentImageUrl() {
      if (this.currentImage) {
        return this.currentImage.objectUrl || this.currentImage.url || '';
      }
      return this.imageUrl || '';
    },
    imageStyle() {
      return {
        transform: `scale(${this.scale})`
      };
    }
  },
  watch: {
    activeImageId(newVal) {
      this.currentImageId = newVal;
    },
    images: {
      immediate: true,
      handler() {
        if (!this.hasImages) {
          this.currentImageId = null;
          return;
        }
        if (!this.currentImageId || !this.images.some(img => img.id === this.currentImageId)) {
          this.currentImageId = this.images[0].id;
          this.emitActiveChange();
        }
      }
    },
    modelValue(newVal) {
      if (!newVal) {
        this.scale = 1;
      }
    }
  },
  methods: {
    handleClose() {
      this.scale = 1;
      this.$emit('update:modelValue', false);
      this.$emit('close');
    },
    selectImage(imageId) {
      if (!imageId || imageId === this.currentImageId) return;
      this.currentImageId = imageId;
      this.emitActiveChange();
    },
    emitActiveChange() {
      this.$emit('update:activeImageId', this.currentImageId);
    },
    showPreviousImage() {
      if (!this.hasImages || this.images.length <= 1) return;
      const currentIndex = this.images.findIndex(img => img.id === this.currentImageId);
      const prevIndex = currentIndex > 0 ? currentIndex - 1 : this.images.length - 1;
      this.currentImageId = this.images[prevIndex].id;
      this.emitActiveChange();
    },
    showNextImage() {
      if (!this.hasImages || this.images.length <= 1) return;
      const currentIndex = this.images.findIndex(img => img.id === this.currentImageId);
      const nextIndex = currentIndex === -1 || currentIndex === this.images.length - 1 ? 0 : currentIndex + 1;
      this.currentImageId = this.images[nextIndex].id;
      this.emitActiveChange();
    },
    rotate(direction) {
      if (!this.allowRotate || !this.currentImageId) return;
      this.$emit('rotate', {
        direction,
        memberId: this.memberId,
        imageId: this.currentImageId
      });
    },
    deleteImage() {
      if (!this.showDelete || !this.currentImageId) return;
      this.$emit('delete-image', {
        memberId: this.memberId,
        imageId: this.currentImageId
      });
    },
    setPrimary() {
      if (!this.showSetPrimary || !this.currentImageId) return;
      this.$emit('set-primary', {
        memberId: this.memberId,
        imageId: this.currentImageId
      });
    },
    handleFileSelect(event) {
      const files = event?.target?.files;
      if (!this.allowUpload || !files || files.length === 0) {
        return;
      }
      this.$emit('upload-images', {
        memberId: this.memberId,
        files
      });
      event.target.value = '';
    },
    resetZoom() {
      this.scale = 1;
    }
  }
};
</script>

<style scoped>
.image-viewer-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.image-main {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.image-main.has-images {
  min-height: 260px;
}

.image-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 220px;
  background: var(--surface-muted);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  overflow: hidden;
  position: relative;
}

.viewer-image {
  max-width: 100%;
  max-height: 45vh;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.no-image {
  padding: 2rem;
  text-align: center;
  color: var(--text-muted);
  font-style: italic;
}

.nav-button {
  border: 1px solid var(--border-color);
  background: rgba(255, 255, 255, 0.88);
  color: var(--text-color);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  cursor: pointer;
  transition: background 0.2s ease, border-color 0.2s ease;
  margin: 0 0.5rem;
}

.nav-button:hover {
  background: var(--surface-color);
  border-color: var(--primary-soft);
}

.image-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  justify-content: center;
}

.action-btn {
  padding: 0.5rem 1.25rem;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  background: var(--surface-color);
  color: var(--text-color);
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(47, 122, 95, 0.1);
  border-color: var(--primary-soft);
  color: var(--primary-strong);
}

.action-btn--danger {
  border-color: rgba(200, 74, 56, 0.24);
  color: #8b3327;
}

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

.upload-section {
  display: flex;
  justify-content: center;
}

.upload-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.upload-label {
  position: relative;
  padding: 0.6rem 1.4rem;
  border: 1px dashed var(--border-color);
  border-radius: 10px;
  cursor: pointer;
  color: var(--text-color);
  background: var(--surface-muted);
  display: inline-block;
  font-size: 0.95rem;
  transition: border 0.2s ease, background 0.2s ease;
}

.upload-label:hover {
  border-color: var(--primary-soft);
  background: rgba(47, 122, 95, 0.1);
}

.upload-label input {
  position: absolute;
  opacity: 0;
  pointer-events: none;
  width: 0;
  height: 0;
}

.thumbnail-strip {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  justify-content: center;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  position: relative;
  border: 2px solid transparent;
  transition: transform 0.2s ease, border 0.2s ease;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail--active {
  border-color: var(--primary-color);
  transform: scale(1.05);
}

.thumbnail--primary {
  box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.5);
}

.thumbnail-badge {
  position: absolute;
  bottom: 4px;
  right: 4px;
  background: rgba(47, 122, 95, 0.9);
  color: var(--text-on-primary);
  padding: 2px 6px;
  font-size: 0.65rem;
  border-radius: 12px;
}

.extra-content {
  width: 100%;
  border-top: 1px solid var(--border-color);
  padding-top: 1rem;
}

.btn-secondary {
  padding: 0.5rem 1.5rem;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  font-size: 0.875rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  background: var(--surface-color);
  color: var(--text-color);
}

.btn-secondary:hover {
  background: var(--surface-muted);
  border-color: var(--primary-soft);
}

@media (max-width: 768px) {
  .viewer-image {
    max-height: 35vh;
  }

  .image-main {
    flex-direction: column;
  }

  .nav-button {
    position: static;
  }
}
</style>
