import { Component, inject, OnInit, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { Trip, TripsApiService } from '../trips-api.service';

@Component({
  selector: 'app-trips-list',
  standalone: true,
  imports: [RouterLink, FormsModule],
  templateUrl: './trips-list.html',
})
export class TripsList implements OnInit {
  private readonly tripsApi = inject(TripsApiService);

  readonly trips = signal<Trip[]>([]);
  readonly newTripName = signal('');

  ngOnInit(): void {
    this.tripsApi.listTrips().subscribe((trips) => this.trips.set(trips));
  }

  createTrip(): void {
    const name = this.newTripName().trim();
    if (!name) return;
    this.tripsApi.createTrip({ name }).subscribe((trip) => {
      this.trips.update((trips) => [...trips, trip]);
      this.newTripName.set('');
    });
  }
}
