import { Component, inject, OnInit, signal } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { Trip, TripMember, TripsApiService } from '../trips-api.service';

@Component({
  selector: 'app-trip-detail',
  standalone: true,
  imports: [],
  templateUrl: './trip-detail.html',
})
export class TripDetail implements OnInit {
  private readonly tripsApi = inject(TripsApiService);
  private readonly route = inject(ActivatedRoute);
  private tripId!: string;

  readonly trip = signal<Trip | undefined>(undefined);
  readonly members = signal<TripMember[]>([]);
  readonly conflictError = signal(false);

  ngOnInit(): void {
    this.tripId = this.route.snapshot.paramMap.get('tripId') as string;
    this.tripsApi.getTrip(this.tripId).subscribe((trip) => this.trip.set(trip));
    this.tripsApi.listMembers(this.tripId).subscribe((members) => this.members.set(members));
  }

  rename(name: string): void {
    const current = this.trip();
    if (!current) return;
    this.conflictError.set(false);
    this.tripsApi.updateTrip(this.tripId, { name, version: current.version }).subscribe({
      next: (updated) => this.trip.set(updated),
      error: (error: HttpErrorResponse) => {
        if (error.status === 409) {
          this.conflictError.set(true);
        }
      },
    });
  }
}
