import { ChangeDetectionStrategy, Component, EventEmitter, Output, computed, input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { ButtonComponent } from '../../../../../shared/ui/button/button.component';
import { InputComponent } from '../../../../../shared/ui/input/input.component';
import { FormFieldComponent } from '../../../../../shared/ui/form-field/form-field.component';
import { ToggleComponent } from '../../../../../shared/ui/toggle/toggle.component';
import { DialogComponent } from '../../../../../shared/ui/dialog/dialog.component';
import { BadgeComponent } from '../../../../../shared/ui/badge/badge.component';
import { MediaAsset } from '../../../../../core/media/models/media-asset.model';
import { MediaUsageEntry } from '../../../../../core/media/media-usage.service';

export interface AssetDetailsPatch {
  altText?: Record<string, string>;
  caption?: string;
  description?: string;
  decorative?: boolean;
}

@Component({
  selector: 'app-asset-details-drawer',
  standalone: true,
  imports: [FormsModule, TranslatePipe, ButtonComponent, InputComponent, FormFieldComponent, ToggleComponent, DialogComponent, BadgeComponent],
  templateUrl: './asset-details-drawer.component.html',
  styleUrl: './asset-details-drawer.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AssetDetailsDrawerComponent {
  readonly asset = input<MediaAsset | null>(null);
  readonly usages = input<MediaUsageEntry[]>([]);

  @Output() close = new EventEmitter<void>();
  @Output() save = new EventEmitter<AssetDetailsPatch>();
  @Output() remove = new EventEmitter<void>();

  readonly isImage = computed(() => this.asset()?.mimeType.startsWith('image/') ?? false);
  readonly dimensionsLabel = computed(() => {
    const asset = this.asset();
    return asset?.width && asset?.height ? `${asset.width}×${asset.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`;
  }

  formatDate(iso: string): string {
    return new Date(iso).toLocaleString();
  }

  onAltChange(value: string): void {
    const asset = this.asset();
    if (!asset) return;
    this.save.emit({ altText: { ...(asset.altText ?? {}), en: value } });
  }

  onCaptionChange(value: string): void {
    this.save.emit({ caption: value });
  }

  onDescriptionChange(value: string): void {
    this.save.emit({ description: value });
  }

  onDecorativeChange(value: boolean): void {
    this.save.emit({ decorative: value });
  }
}
