import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { Product } from '../../../../../core/products/models/product-domain.model';
import { getMainImage, onImageError } from '../../../../../utils/item.utils';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';

type ProductMediaType = 'image' | 'video' | 'pdf' | 'manual' | 'warranty';

interface GalleryMediaItem {
  id: string;
  type: ProductMediaType;
  url: string;
  thumbnailUrl: string;
  alt: string;
}

@Component({
  selector: 'app-product-gallery',
  standalone: true,
  imports: [TranslatePipe],
  templateUrl: './product-gallery.component.html',
  styleUrls: ['./product-gallery.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductGalleryComponent {
  readonly onImageError = onImageError;

  @Input({ required: true }) product!: Product;
  @Input() selectedIndex = 0;

  @Output() selectedIndexChange = new EventEmitter<number>();
  @Output() zoomRequested = new EventEmitter<number>();
  @Output() fullscreenRequested = new EventEmitter<number>();

  readonly getMainImage = getMainImage;

  private touchStartX = 0;
  private touchStartY = 0;

  get media(): GalleryMediaItem[] {
    if (this.product.media?.length) {
      return this.product.media.map((item, index) => ({
        id: item.id ?? `media-${index}`,
        type: item.type,
        url: item.url,
        thumbnailUrl: item.thumbnailUrl ?? item.url,
        alt: item.alt || item.title || this.product.name,
      }));
    }

    if (this.product.photos?.length) {
      return this.product.photos.map((item, index) => ({
        id: item.photo ?? `photo-${index}`,
        type: item.video ? 'video' : this.resolveLegacyType(item.type),
        url: item.url,
        thumbnailUrl: item.url,
        alt: this.product.name,
      }));
    }

    return [{
      id: 'fallback-image',
      type: 'image',
      url: this.getMainImage(this.product),
      thumbnailUrl: this.getMainImage(this.product),
      alt: this.product.name,
    }];
  }

  select(index: number): void {
    this.selectedIndexChange.emit(index);
  }

  onTouchStart(event: TouchEvent): void {
    if (event.touches.length === 0) {
      return;
    }

    this.touchStartX = event.touches[0].clientX;
    this.touchStartY = event.touches[0].clientY;
  }

  onTouchEnd(event: TouchEvent): void {
    if (event.changedTouches.length === 0 || this.media.length <= 1) {
      return;
    }

    const deltaX = event.changedTouches[0].clientX - this.touchStartX;
    const deltaY = event.changedTouches[0].clientY - this.touchStartY;

    if (Math.abs(deltaX) < 36 || Math.abs(deltaX) < Math.abs(deltaY)) {
      return;
    }

    const direction = deltaX > 0 ? -1 : 1;
    const next = Math.min(Math.max(0, this.selectedIndex + direction), this.media.length - 1);
    if (next !== this.selectedIndex) {
      this.selectedIndexChange.emit(next);
    }
  }

  private resolveLegacyType(type: string | undefined): ProductMediaType {
    const normalized = (type ?? '').toLowerCase();
    if (normalized === 'video') return 'video';
    if (normalized === 'pdf') return 'pdf';
    if (normalized === 'manual') return 'manual';
    if (normalized === 'warranty') return 'warranty';
    return 'image';
  }
}
