import { CommonModule, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
} from '@angular/forms';
import {
  ActivatedRoute,
  NavigationEnd,
  Router,
  RouterLink,
} from '@angular/router';
import {
  catchError,
  debounceTime,
  distinctUntilChanged,
  of,
  switchMap,
} from 'rxjs';
import { Pin } from '../../model/Pin';
import { LocalStorageService } from '../../services/local-storage/local-storage.service';
import { PinService } from '../../services/pin/pin.service';
import { AddPinPopupComponent } from '../add-pin-popup/add-pin-popup.component';
import { FriendPageComponent } from '../friend-page/friend-page.component';

@Component({
  selector: 'app-navbar',
  imports: [
    AddPinPopupComponent,
    NgIf,
    FriendPageComponent,
    CommonModule,
    ReactiveFormsModule,
    RouterLink,
  ],
  templateUrl: './navbar.component.html',
})
export class NavbarComponent implements OnInit {
  isTimeline: boolean = false;

  isSearchOpen: boolean = false;
  isNavbarOpen: boolean = false;

  toggleNavbar() {
    this.isNavbarOpen = !this.isNavbarOpen;
    this.isSearchOpen = false;
  }

  toggleSearch() {
    this.isSearchOpen = !this.isSearchOpen;
    this.isNavbarOpen = false;
  }

  pins: Pin[] = [];
  pinsFiltered: Pin[] = [];
  inputFocus: Boolean = false;
  searchForm: FormGroup;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private localStorageService: LocalStorageService,
    private pinService: PinService,
    private fb: FormBuilder
  ) {
    this.searchForm = this.fb.group({
      searchControl: new FormControl(''),
    });
  }

  ngOnInit(): void {
    this.pins = this.pinService.getPins().subscribe((pins: Pin[]) => {
      this.pins = pins;
    });

    this.isTimeline = this.router.url === '/timeline';
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.isTimeline = event.url === '/timeline';
      }
    });

    // Initialise la barre de recherche avec debounce et distinctUntilChanged
    this.searchForm
      .get('searchControl')
      ?.valueChanges.pipe(
        debounceTime(300), // Attendre 300ms après la dernière frappe
        distinctUntilChanged(), // Ignorer si la nouvelle valeur est la même que la précédente
        switchMap((searchTerm) => {
          const trimmedQuery = searchTerm?.trim();
          if (trimmedQuery && trimmedQuery.length > 1) {
            return of(this.filterPins(trimmedQuery));
          }
          return of([]);
        }),
        catchError((error) => {
          console.error(
            'Erreur lors de la récupération des suggestions :',
            error
          );
          return of([]);
        })
      )
      .subscribe((filteredPins) => {
        this.pinsFiltered = filteredPins;
      });
  }

  filterPins(searchTerm: string): Pin[] {
    const filteredPins: Pin[] = [];

    if (this.pins.length === 0) {
      this.pins = this.pinService.getPins();
    }

    this.pins.forEach((pin: Pin) => {
      if (
        pin.title &&
        pin.title.toLowerCase().includes(searchTerm.toLowerCase())
      ) {
        filteredPins.push(pin);
      }
    });

    return filteredPins;
  }

  clickSuggestion(pin: Pin): void {
    this.searchForm.reset();

    const queryParams = { pin: pin.id }; // Remplacer "id" par la bonne propriété si nécessaire
    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: queryParams,
      queryParamsHandling: 'merge', // Conserve les autres paramètres de requête
    });
  }

  onFocus(): void {
    this.inputFocus = true;
  }

  onBlur(): void {
    setTimeout(() => {
      this.inputFocus = false;
    }, 200); // Petit délai pour laisser l'utilisateur cliquer
  }

  public logout() {
    this.localStorageService.removeToken();
    this.localStorageService.removeUsername();
    this.router.navigate(['/']);
  }
}
