import { DatePipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ApiService, MaintenanceDetail } from '../../core/api.service';
import { LangService } from '../../core/lang.service';

@Component({
  selector: 'app-maintenance-detail',
  standalone: true,
  imports: [DatePipe, FormsModule, RouterLink],
  template: `
    <a routerLink="/maintenance" class="back">‹ {{ lang.t('nav_maintenance') }}</a>

    @if (loading()) { <p class="muted">{{ lang.t('loading') }}</p> }
    @else { @if (req(); as r) {
      <div class="head fade-in">
        <div>
          <h1>{{ r.code }} · {{ r.title }}</h1>
          <p class="muted">{{ lang.t('mcat_' + r.category) }} · <span class="badge {{ prioClass(r.priority) }}">{{ lang.t('prio_' + r.priority) }}</span></p>
        </div>
        <span class="badge big {{ statusClass(r.status) }}">{{ lang.t('mst_' + r.status) }}</span>
      </div>

      <div class="grid">
        <div class="card card-pad fade-in">
          <h3>{{ lang.t('details') }}</h3>
          @if (r.description) { <p>{{ r.description }}</p> }
          <div class="kv"><span class="muted">{{ lang.t('col_due') }}</span><span>{{ r.due_at ? (r.due_at | date:'short') : '—' }}</span></div>
          @if (r.resolved_at) { <div class="kv"><span class="muted">{{ lang.t('mst_resolved') }}</span><span>{{ r.resolved_at | date:'short' }}</span></div> }

          @if (r.flow.length) {
            <h4 class="wf">{{ lang.t('move_to') }}</h4>
            <div class="wf-btns">
              @for (to of r.flow; track to) {
                <button class="btn btn--ghost btn--sm" [disabled]="busy()" (click)="move(to)">{{ lang.t('mst_' + to) }}</button>
              }
            </div>
            <div class="field"><input [(ngModel)]="comment" [placeholder]="lang.t('add_comment')" /></div>
          }
        </div>

        <div class="card card-pad fade-in">
          <h3>{{ lang.t('update_trail') }}</h3>
          @for (u of r.updates; track u.id) {
            <div class="upd">
              <div class="dot"></div>
              <div>
                @if (u.to) { <strong>{{ u.from ? (lang.t('mst_' + u.from) + ' → ') : '' }}{{ lang.t('mst_' + u.to) }}</strong> }
                @if (u.comment) { <div>{{ u.comment }}</div> }
                <small class="muted">{{ u.at | date:'short' }}</small>
              </div>
            </div>
          }
        </div>
      </div>
    } }
  `,
  styles: [`
    .back { display: inline-block; margin-bottom: 16px; color: var(--ink-soft); font-weight: 600; }
    .head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; margin-bottom: 22px; }
    .head h1 { font-size: 1.3rem; margin-bottom: 4px; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 20px; align-items: start; }
    h3 { margin-bottom: 14px; } .wf { margin: 18px 0 10px; }
    .kv { display: flex; justify-content: space-between; gap: 14px; padding: 8px 0; border-bottom: 1px dashed var(--line); }
    .wf-btns { display: flex; flex-wrap: wrap; gap: 8px; }
    .field { margin-top: 12px; } .field input { width: 100%; padding: 9px 11px; border: 1px solid var(--line); border-radius: 8px; font-family: inherit; }
    .badge { font-size: .72rem; font-weight: 700; padding: 3px 10px; border-radius: 999px; } .badge.big { font-size: .8rem; padding: 5px 14px; }
    .b-urgent { background: #fde6e6; color: #b5281a; } .b-high { background: #fdeede; color: #b5691a; }
    .b-medium { background: #e9f0fb; color: #2a5db0; } .b-low { background: #eef2ee; color: #557; }
    .b-open { background: #e9f0fb; color: #2a5db0; } .b-done { background: #e7f5ec; color: #1d7a46; } .b-grey { background: #efeae0; color: #777; }
    .upd { display: flex; gap: 12px; padding: 10px 0; border-bottom: 1px dashed var(--line); }
    .upd:last-child { border-bottom: none; }
    .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--gold); margin-top: 6px; flex: none; }
  `],
})
export class MaintenanceDetailComponent {
  lang = inject(LangService);
  private api = inject(ApiService);
  private route = inject(ActivatedRoute);

  req = signal<MaintenanceDetail | null>(null);
  loading = signal(true);
  busy = signal(false);
  comment = '';
  private id = Number(this.route.snapshot.paramMap.get('id'));

  constructor() { this.reload(); }
  reload(): void {
    this.api.maintenanceDetail(this.id).subscribe({
      next: (r) => { this.req.set(r.data.request); this.loading.set(false); },
      error: () => this.loading.set(false),
    });
  }
  move(to: string): void {
    this.busy.set(true);
    this.api.transitionMaintenance(this.id, { to, comment: this.comment || undefined }).subscribe({
      next: (r) => { this.req.set(r.data.request); this.comment = ''; this.busy.set(false); },
      error: (e) => { this.busy.set(false); alert(e?.error?.message || 'Error'); },
    });
  }
  prioClass(p: string): string { return ({ urgent: 'b-urgent', high: 'b-high', medium: 'b-medium', low: 'b-low' } as Record<string, string>)[p] || 'b-low'; }
  statusClass(s: string): string { return s === 'verified' ? 'b-done' : (s === 'cancelled' ? 'b-grey' : 'b-open'); }
}
