import { AsyncPipe, KeyValuePipe } from '@angular/common'
import { ChangeDetectionStrategy, Component, inject } from '@angular/core'
import { toSignal } from '@angular/core/rxjs-interop'
import { i18nPipe } from '@start9labs/shared'
import { TuiMapperPipe } from '@taiga-ui/cdk'
import { TuiIcon, TuiLoader, TuiTitle, TuiCell } from '@taiga-ui/core'
import { TuiAvatar } from '@taiga-ui/kit'
import { PatchDB } from 'patch-db-client'
import { take } from 'rxjs'
import { ToManifestPipe } from 'src/app/routes/portal/pipes/to-manifest'
import { DataModel } from 'src/app/services/patch-db/data-model'

@Component({
  selector: '[backupProgress]',
  template: `
    <header>{{ 'Backup Progress' | i18n }}</header>
    @for (pkg of pkgs() | keyvalue; track $index) {
      @if (backupProgress()?.[pkg.key]; as progress) {
        <div tuiCell>
          <span tuiAvatar appearance="action-grayscale">
            <img alt="" [src]="pkg.value.icon" />
          </span>
          <span tuiTitle>
            {{ (pkg.value | toManifest).title }}
          </span>
          <span class="status">
            @if (progress.complete) {
              <tui-icon icon="@tui.check" class="g-positive" />
              {{ 'complete' | i18n }}
            } @else {
              @if ((pkg.key | tuiMapper: toStatus | async) === 'backing-up') {
                <tui-loader size="s" />
                {{ 'backing up' | i18n }}
              } @else {
                <tui-icon icon="@tui.clock" />
                {{ 'waiting' | i18n }}
              }
            }
          </span>
        </div>
      }
    }
  `,
  styles: `
    :host {
      max-width: 36rem;
    }

    .status {
      display: flex;
      align-items: center;
      gap: 0.25rem;
      margin-inline-start: auto;
      white-space: nowrap;
    }

    .status tui-icon {
      font-size: 1rem;
    }
  `,
  host: { class: 'g-card' },
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    KeyValuePipe,
    AsyncPipe,
    TuiCell,
    TuiAvatar,
    TuiTitle,
    TuiIcon,
    TuiLoader,
    TuiMapperPipe,
    ToManifestPipe,
    i18nPipe,
  ],
})
export class BackupProgressComponent {
  private readonly patch = inject<PatchDB<DataModel>>(PatchDB)

  readonly pkgs = toSignal(this.patch.watch$('packageData').pipe(take(1)))
  readonly backupProgress = toSignal(
    this.patch.watch$('serverInfo', 'statusInfo', 'backupProgress'),
  )

  readonly toStatus = (pkgId: string) =>
    this.patch.watch$('packageData', pkgId, 'statusInfo', 'desired', 'main')
}
