import { Component, effect, inject, input, OnInit, signal } from '@angular/core';
import { MapComponent, MapMarker } from '@app/shared/components/map/map.component';
import { ProfileViewModel } from '@app/adapters/profiles/profile.presenter.model';
import { LocationFacade } from '@app/adapters/location/location.facade';
import { Router } from '@angular/router';

@Component({
  selector: 'app-profile-list-map',
  standalone: true,
  imports: [MapComponent],
  providers: [LocationFacade],
  templateUrl: './profile-list-map.component.html',
  styleUrl: './profile-list-map.component.scss',
})
export class ProfileListMapComponent implements OnInit {
  readonly profiles = input<ProfileViewModel[]>();
  private readonly locationFacade = inject(LocationFacade);
  private readonly router = inject(Router); // Injection du Router

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

  constructor() {
    effect(
      () => {
        const state = this.locationState();
        const profiles = this.profiles();
        if (profiles) {
          this.markers.set(this.toMapMarker(profiles));
        }

        // Centrer la carte par rapport à sa position lorsque les coordonnées changent
        if (state.coordinates) {
          this.locationState.set({ ...this.locationState(), coordinates: state.coordinates });
        }
      },
      { allowSignalWrites: true }
    );
  }

  ngOnInit() {}

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

  // Nouvelle méthode pour gérer le clic sur "Voir plus"
  onMarkerClicked(marker: MapMarker): void {
    // Redirection vers la page détail
    this.router.navigate(['/profiles', marker.profile!.slug], {
      state: { user: marker.profile!.userViewModel, profile: marker.profile! },
    });
  }

  private toMapMarker(profiles: ProfileViewModel[]): MapMarker[] {
    return profiles
      .filter((profile: ProfileViewModel) => {
        return (
          profile.settings!.allowGeolocation &&
          profile.coordonnees &&
          profile.coordonnees!.longitude != 0 &&
          profile.coordonnees!.latitude != 0
        );
      })
      .map((currentProfile: ProfileViewModel) => {
        return {
          id: currentProfile.id,
          coordinates: currentProfile.coordonnees!,
          title: currentProfile.fullName,
          description: currentProfile.bio,
          profile: currentProfile,
        };
      });
  }
}
