import { ChangeDetectionStrategy, Component, EventEmitter, Output, computed, input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { ButtonComponent } from '../../../../../shared/ui/button/button.component';
import { BadgeComponent } from '../../../../../shared/ui/badge/badge.component';
import { CardComponent } from '../../../../../shared/ui/card/card.component';
import { ToggleComponent } from '../../../../../shared/ui/toggle/toggle.component';
import { MediaAsset } from '../../../../../core/media/models/media-asset.model';

export type AssetTileLayout = 'grid' | 'list';

@Component({
  selector: 'app-asset-tile',
  standalone: true,
  imports: [FormsModule, TranslatePipe, ButtonComponent, BadgeComponent, CardComponent, ToggleComponent],
  templateUrl: './asset-tile.component.html',
  styleUrl: './asset-tile.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AssetTileComponent {
  readonly asset = input.required<MediaAsset>();
  readonly layout = input<AssetTileLayout>('grid');
  readonly selected = input(false);
  readonly usageCount = input<number | null>(null);
  readonly isUnused = input(false);
  readonly missingAlt = input(false);

  @Output() open = new EventEmitter<void>();
  @Output() toggleSelected = new EventEmitter<boolean>();
  @Output() remove = new EventEmitter<void>();

  readonly isImage = computed(() => this.asset().mimeType.startsWith('image/'));

  readonly dimensionsLabel = computed(() => {
    const { width, height } = this.asset();
    return width && height ? `${width}×${height}` : null;
  });

  formatSize(bytes: number): string {
    if (bytes < 1024) {
      return `${bytes} B`;
    }
    if (bytes < 1024 * 1024) {
      return `${(bytes / 1024).toFixed(1)} KB`;
    }
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
}
