import { Component, computed, input, output } from '@angular/core';
import type { Upload } from '@shared/upload/upload.machine';
import { DocumentChipComponent } from '../document-chip/document-chip.component';
import { UploadProgressBarComponent } from '../upload-progress-bar/upload-progress-bar.component';

/** Molecule: one upload row — its chip plus a progress bar while uploading. Pure UI:
    forwards `remove`/`retry` from the chip. */
@Component({
  selector: 'app-single-upload',
  imports: [DocumentChipComponent, UploadProgressBarComponent],
  styles: [`
    :host { display: flex; flex-direction: column; gap: var(--rhc-space-max-sm); }
  `],
  template: `
    <app-document-chip
      [fileName]="upload().fileName"
      [status]="upload().status"
      [previewUrl]="previewUrl()"
      (remove)="remove.emit()"
      (retry)="retry.emit()" />
    @if (progressPct() !== null) {
      <app-upload-progress-bar [progressPct]="progressPct()!" />
    }
  `,
})
export class SingleUploadComponent {
  upload = input.required<Upload>();
  /** Builds a preview URL for a completed upload's documentId (undefined = no link). */
  previewUrlFor = input<(documentId: string) => string | undefined>();

  /** Narrow the status union once, in TS, so the template stays type-safe. */
  protected readonly progressPct = computed<number | null>(() => {
    const status = this.upload().status;
    return status.type === 'uploading' ? status.progressPct : null;
  });

  protected readonly previewUrl = computed<string | undefined>(() => {
    const status = this.upload().status;
    return status.type === 'complete' ? this.previewUrlFor()?.(status.documentId) : undefined;
  });

  remove = output<void>();
  retry = output<void>();
}
