import { Component, OnInit, NgZone } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { Geolocation } from '@capacitor/geolocation';
import { TranslateService } from '@ngx-translate/core';

declare var google: any;

@Component({
  selector: 'app-category',
  templateUrl: './category.page.html',
  styleUrls: ['./category.page.scss'],
  standalone: false
})
export class CategoryPage implements OnInit {

  private loading: any;
  category: any = null;
  //money: number = null;
  //amount: number = null;
  //amount_check = true;
  minyear: string = (new Date().getFullYear() + '-' +  ((new Date().getMonth() + 1) < 10 ? '0' : '') + (new Date().getMonth() + 1) + '-' + (new Date().getDate() < 10 ? '0' : '') + new Date().getDate()).toString();
  maxyear: string | null = null;
  mintime: number = 0;
  maxtime: number = 0;
  setHour: any;
  setDate: any;
  references: string = '';
  details: string = '';
  differenceDate: number = 0;
  differenceHour: number = 0;
  myPosition: any = {};
  myAddress: string | null = null;
  myIntnumber: string | null = null;
  addressAutocomplete: string = '';
  placesSearch: any = '';
  showif = true;

  constructor(
    private authService: AuthService,
    private navCtrl: NavController,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private activatedRoute: ActivatedRoute,
    private translateService: TranslateService,
    private ngZone: NgZone,
    private loadingCtrl: LoadingController
  ) {
    console.log(google);
  }

  ngOnInit() {
    this.category = this.activatedRoute.snapshot.paramMap.get('category');
    this.ichambaService.getParameters()
      .subscribe( (data: any) => {
        this.mintime = data['min_time'];
        this.maxtime = data['max_time'];
      });
    this.getCurrentLocation();
    console.log(this.minyear);
    // Máximo 2 días de anticipación
    const maxDate = new Date();
    maxDate.setDate(maxDate.getDate() + 2);
    this.maxyear = maxDate.toISOString().slice(0, 10);
    console.log(this.maxyear);
  }

  async getCurrentLocation() {
    try {
      // Request permissions first
      const permissionStatus = await Geolocation.checkPermissions();
      if (permissionStatus.location !== 'granted') {
        await Geolocation.requestPermissions();
      }

      const position = await Geolocation.getCurrentPosition({
        enableHighAccuracy: true,
        timeout: 30000
      });

      console.log(position);
      this.myPosition = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude
      };
      this.doGeocode();
    } catch (error) {
      console.log(this.translateService.instant('alerts.geo_error') + error);
    }
  }

  doGeocode() {
    // Use Google Maps JavaScript API for geocoding
    const geocoder = new google.maps.Geocoder();
    const latlng = { lat: this.myPosition.latitude, lng: this.myPosition.longitude };

    geocoder.geocode({ location: latlng }, (results: any, status: any) => {
      this.ngZone.run(() => {
        if (status === 'OK' && results[0]) {
          const address = results[0].formatted_address;
          console.log("data_: ", address);
          this.myAddress = address;
          this.addressAutocomplete = address; // Sincronizar con el input
        }
      });
    });
  }

  /* check (ev: any) {
    this.amount = parseFloat(ev.target.value.replace(",", ""));
    console.log(this.amount);
    if (this.amount < 150) {
      this.amount_check = false;
    } else {
      this.amount_check = true;
    }
  }*/

  changehour (ev: any) {
    console.log(this.setHour);
  }

  changedate (ev: any) {
    console.log(ev.target.value);
    let current_date = (new Date().toISOString().slice(0, 10)).toString();
    let selected_date = (new Date(this.setDate).toISOString().slice(0, 10)).toString();
    this.differenceDate = (Number(new Date(selected_date)) - Number(new Date(current_date)));
    console.log(this.differenceDate);
  }

  autocomplete(ev: any) {
    if (!this.addressAutocomplete.trim().length) {
      this.placesSearch = null;
    }
    console.log(this.addressAutocomplete)
    new google.maps.places.AutocompleteService().getPredictions({ input: this.addressAutocomplete }, (predictions: any) => {
      this.ngZone.run(() => {
        this.placesSearch = predictions;
        console.log(predictions);
      });
    });
  }

  geoloc(place_id: string, place_description: string) {
    this.myAddress = place_description;
    this.addressAutocomplete = place_description; // Sincronizar con el input
    console.log(place_id);
    this.hidelist();
    new google.maps.Geocoder().geocode({ placeId: place_id }, (coordinates: any) => {
      this.ngZone.run(() => {
        console.log(coordinates[0].geometry.location.lat() + ", " + coordinates[0].geometry.location.lng());
        this.myPosition = {
          latitude: coordinates[0].geometry.location.lat(),
          longitude: coordinates[0].geometry.location.lng()
        }
      });
    });
  }

  addpostulation() {
    // Validar que fecha y hora estén seleccionadas
    if (!this.setDate || !this.setHour) {
      this.alertService.presentToast(this.translateService.instant('alerts.select_date_time') || 'Selecciona fecha y hora');
      return;
    }

    // Calcular diferencia de fecha directamente
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const selectedDate = new Date(this.setDate);
    selectedDate.setHours(0, 0, 0, 0);
    this.differenceDate = selectedDate.getTime() - today.getTime();

    // Calcular diferencia de hora
    this.differenceHour = (new Date(this.setHour).getTime() - new Date().getTime());

    console.log("differenceDate:", this.differenceDate);
    console.log("differenceHour:", this.differenceHour);
    console.log("mintime:", this.mintime * 3600000);

    // Máximo 2 días de anticipación (172800000 ms = 2 días)
    const maxDays = 2 * 24 * 60 * 60 * 1000;
    console.log("maxDays:", maxDays);

    // Validación de tiempo mínimo (mismo día y menos de mintime horas)
    if (this.differenceDate < 86400000 && this.differenceHour < (this.mintime * 3600000)) {
      this.alertService.presentToast(this.translateService.instant('alerts.categories_mintime'));
    } else if (this.differenceDate <= maxDays) {
        if (this.myAddress && this.myPosition.latitude && this.myPosition.longitude) {
            this.loadingCtrl.create().then((overlay) => {
              this.loading = overlay;
              this.loading.present();
            });

            if (!Number.isInteger(parseInt(this.myIntnumber ?? ''))) {
              this.myIntnumber = null;
            }
            this.ichambaService.addPostulation(this.category, this.myAddress!, this.myIntnumber ?? '', this.references, this.myPosition.latitude, this.myPosition.longitude, this.setDate, this.setHour, this.details).subscribe(
              (data: any) => {
                if (this.loading) this.loading.dismiss();
                if (data['message'] == 'No providers') {
                  this.alertService.presentToast(this.translateService.instant('alerts.no_provider'));
                } else {
                  this.navCtrl.navigateRoot('/dashboard');
                  this.alertService.presentToast(this.translateService.instant('alerts.categories_success'));
                }
              }, (error: any) => {
                if (this.loading) this.loading.dismiss();
                this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
              });
        } else {
          this.alertService.presentToast(this.translateService.instant('alerts.valid_address'));
        }
    } else {
      this.alertService.presentToast(this.translateService.instant('alerts.categories_maxtime'));
    }
  }

  showlist() {
    this.showif = true;
  }

  hidelist() {
    this.showif = false;
  }

}
