import { Component, effect, inject, input, OnInit, signal } from '@angular/core';
import { MapComponent, MapMarker } from '@app/shared/components/map/map.component';
import { Coordinates, CoordinatesValidator } from '@app/domain/localisation/coordinates.model';
import { LocationFacade } from '@app/adapters/location/location.facade';
import { ProfileFacade } from '@app/adapters/profiles/profile.facade';
import { ProfileViewModel } from '@app/adapters/profiles/profile.presenter.model';
import { ActionType } from '@app/domain/action-type.util';

@Component({
  selector: 'app-my-profile-map',
  standalone: true,
  imports: [MapComponent],
  providers: [LocationFacade],
  templateUrl: './my-profile-map.component.html',
  styleUrl: './my-profile-map.component.scss',
})
export class MyProfileMapComponent implements OnInit {
  readonly profile = input<ProfileViewModel>();
  private readonly locationFacade = inject(LocationFacade);
  private readonly profileFacade = inject(ProfileFacade);

  private readonly loading = this.profileFacade.loading;
  private readonly error = this.profileFacade.error;

  protected readonly locationState = this.locationFacade.locationState;
  protected readonly markers = signal<MapMarker[]>([]);

  private initializedFromProfile = false;

  constructor() {
    effect(
      () => {
        const profile = this.profile();
        const state = this.locationState();

        // Initialiser une seule fois quand profile est disponible
        if (!this.initializedFromProfile && profile?.coordonnees) {
          this.initializedFromProfile = true;
          this.locationState.set({
            ...state,
            coordinates: profile.coordonnees,
          });
        }

        // Mettre à jour les markers quand les coordonnées changent
        if (state.coordinates) {
          this.updateMarkers(state.coordinates);
        }

        if (!this.loading().isLoading) {
          switch (this.loading().action) {
            case ActionType.UPDATE:
              if (!this.error().hasError) {
              }
              break;
          }
        }
      },
      { allowSignalWrites: true }
    );
  }

  ngOnInit() {}

  onSaveLocation() {
    const currentLocation = this.locationState().coordinates;
    if (currentLocation === null) return;
    this.profileFacade.updateCoordinate(
      this.profile()!.id!,
      currentLocation.latitude,
      currentLocation.longitude
    );
  }

  onLocationSelected(coordinates: Coordinates): void {
    this.locationState.set({ ...this.locationState(), coordinates: coordinates });
  }

  onGetCurrentLocation(): void {
    this.locationFacade.getCurrentLocation();
  }

  private updateMarkers(coordinates: Coordinates): void {
    const marker: MapMarker[] = [
      {
        id: this.profile()!.id,
        coordinates: coordinates,
        title: this.profile()!.fullName,
        description: CoordinatesValidator.format(coordinates),
        profile: this.profile()!,
      },
    ];
    this.markers.set(marker);
  }
}
