import { CommonModule } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
} from '@angular/forms';
import { of } from 'rxjs';
import {
  catchError,
  debounceTime,
  distinctUntilChanged,
  switchMap,
} from 'rxjs/operators';
import { AddPinService } from '../../services/add-pin.service';
import { AutocompleteService } from '../../services/auto-complete.service';
import { DragDropComponent } from '../drag-drop/drag-drop.component';

@Component({
  selector: 'app-add-pin-popup',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule, DragDropComponent],
  templateUrl: './add-pin-popup.component.html',
})
export class AddPinPopupComponent implements OnInit {
  form: FormGroup;
  suggestions: any[] = [];
  inputFocused: boolean = false;
  @Input() isHomePage: boolean = false;
  files: any[] = [];

  constructor(
    private fb: FormBuilder,
    private autocompleteService: AutocompleteService,
    private addPinService: AddPinService
  ) {
    this.form = this.fb.group({
      title: new FormControl(''),
      description: new FormControl(''),
      location: new FormControl(''),
      files: new FormControl(null),
    });
  }

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

  onBlur(): void {
    setTimeout(() => {
      this.inputFocused = false; // Désactiver le focus après un petit délai pour permettre un clic sur la liste
    }, 200);
  }

  ngOnInit(): void {
    this.form
      .get('location')
      ?.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((query) => {
          const trimmedQuery = query.trim();
          if (trimmedQuery.length > 2) {
            return this.autocompleteService.getAddressSuggestions(trimmedQuery);
          }
          return of([]);
        }),
        catchError((error) => {
          console.error('Error fetching suggestions:', error);
          return of([]);
        })
      )
      .subscribe((data) => {
        this.suggestions = data;
      });
  }

  selectSuggestion(suggestion: any): void {
    const locationControl = this.form.get('location');
    if (locationControl instanceof FormControl) {
      locationControl.setValue(suggestion.display_name);
    }
    this.suggestions = [];
  }

  onFilesReceived(files: FileList): void {
    this.files = Array.from(files);
  }

  submitForm(): void {
    if (this.form.valid) {
      this.files = this.files.map((file) => {
        return file.name; //TODO: Mettre le hash du fichier
      });

      const pinData = {
        ...this.form.value,
        files: this.files, // Ajoutez les fichiers au payload
      };

      console.log('Form submitted with data:', pinData);

      this.addPinService.addPin(pinData);
    } else {
      console.error('Le formulaire est invalide');
    }
  }
}
