import { Component, computed, input } from '@angular/core';
import type { UploadStatus } from '@shared/upload/upload.machine';
import { UploadStatusIconComponent } from '../upload-status-icon/upload-status-icon.component';

const STATUS_LABELS: Record<UploadStatus['type'], string> = {
  idle: '',
  queued: $localize`:@@upload.status.queued:In wachtrij`,
  uploading: $localize`:@@upload.status.uploading:Bezig met uploaden`,
  complete: $localize`:@@upload.status.complete:Geüpload`,
  failed: $localize`:@@upload.status.failed:Mislukt`,
  deleting: $localize`:@@upload.status.deleting:Bezig met verwijderen`,
  deleted: '',
};

/** Atom: the `.file` block of a CIBG Bestand-upload file row — a status glyph, the
    filename (a download link once complete) and a `.file-meta` line (size + status).
    `display:contents` so `.file` becomes a flex child of the `.file-container` row.
    Pure UI. */
@Component({
  selector: 'app-document-chip',
  imports: [UploadStatusIconComponent],
  styles: [
    `
      :host {
        display: contents;
      }
      .file {
        display: flex;
        flex-direction: column;
        gap: var(--rhc-space-max-xs);
        min-inline-size: 0;
      }
      .file-name {
        word-break: break-all;
      }
    `,
  ],
  template: `
    <div class="file">
      <span class="d-inline-flex align-items-center gap-2">
        <app-upload-status-icon [status]="status().type" />
        @if (previewUrl()) {
          <a class="file-name" [href]="previewUrl()" target="_blank" rel="noopener">{{
            fileName()
          }}</a>
        } @else {
          <span class="file-name">{{ fileName() }}</span>
        }
      </span>
      <span class="file-meta">{{ meta() }}</span>
    </div>
  `,
})
export class DocumentChipComponent {
  fileName = input.required<string>();
  status = input.required<UploadStatus>();
  fileSizeMb = input(0);
  /** When set, the filename is a preview/download link (opens the stored bytes). */
  previewUrl = input<string>();

  /** `.file-meta`: file size + status word (+ the failure reason when failed). */
  protected meta = computed(() => {
    const s = this.status();
    const size = this.fileSizeMb() > 0 ? `${this.fileSizeMb().toFixed(1)} MB` : '';
    const label = s.type === 'failed' && s.reason ? s.reason : STATUS_LABELS[s.type];
    return [size, label].filter(Boolean).join(' · ');
  });
}
