import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { PaginatorState } from 'primeng/paginator';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-hotel-zone-add',
  templateUrl: './hotel-zone-add.component.html',
})
export class HotelZoneAddComponent implements OnInit {
  visible: boolean = false;

  hotelZoneForm:FormGroup;
  ddLoader = {
    country:false,
    city:false,
  };
  CountryList:any[] = [];
  cityList=[];
  timer:any;
  citySelection = true;
  hotelList = [];
  Edit_Id;
  editResp;
  selectedHotelList = [];
  selectedHotelCheck = [];
  SelectedHotels = [];

  constructor(public fb:FormBuilder, public validServ:ValidationService, private apiserv:API, private commonMasterSer:CommonFunctionService, private router:Router, private activateRoute:ActivatedRoute){

  }
    showDialog() {
      this.SelectedHotels = [];
      this.hotelList.forEach(hotelDet=>{
        if(hotelDet.check){
          this.SelectedHotels.push(hotelDet);
        }
      })
      this.visible = true;
    }
      first: number = 0;

    rows: number = 10;

      ngOnInit(): void {
        this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
        this.initform();
        if(this.Edit_Id){
          this.GetById();
        }
      }

    onPageChange(event: PaginatorState) {
        this.first = event.first ?? 0;
        this.rows = event.rows ?? 10;
    }

    GetById(){
       this.apiserv.Get(`/ActivityHotelZone/GetById/${this.Edit_Id}`).subscribe(res => {
          if (res && res.status) {
            this.editResp = res.data;
            let country_obj = {
              country_code : this.editResp.country,
              country_name:this.editResp.countryName
            }
            let city_obj = {
              cityCode:this.editResp.city,
              countryName:this.editResp.countryName,
              cityName:this.editResp.cityName,
            }
            this.CountryList.push(country_obj);
            this.cityList.push(city_obj);

            this.hotelZoneForm.get('Country').setValue(this.editResp.country);
            this.hotelZoneForm.get('City').setValue(this.editResp.city);
            this.hotelZoneForm.get('ZoneName').setValue(this.editResp.zoneName);
            this.hotelZoneForm.get('ZoneName').disable();
            this.getHotelsByCity(true);
          }
        });
    }

    initform(){
      this.hotelZoneForm = this.fb.group({
        ZoneName:this.validServ.required,
        Country:this.validServ.required,
        City:this.validServ.required,
        selectAll:false,
        filterInput:''
      })
    }

    getCountryList(event) {
      if (event.value.length >= 2) {
        this.ddLoader.country = true;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.apiserv.AdminGet(`/MasterSearch/GetAllCountry/en/${event.value}`).subscribe(res => {
            if (res) {
              this.CountryList = res;
              this.ddLoader.country = false;
            }
          });
        }, 500);
      }
    }

    getCityList(event) {
       if (event.value.length >= 2) {
        this.ddLoader.city = true;
        clearTimeout(this.timer);
        let req = {
          "cityName": event.value,
          "languageCode": "EN",
          "lattitude": "0",
          "longitude": "0",
          "CountryCode": this.hotelZoneForm.get('Country').value || '',
        }
        this.timer = setTimeout(() => {
          this.apiserv.PostGo(`/Hotel/GetHotelCities`, req).subscribe(res => {
            if (res) {
              this.cityList = res.cities;
               this.ddLoader.city = false;
            }
          });
        }, 500);
      }
    }

    checkCountrySelection(){
      let val = this.hotelZoneForm.get('Country').value;
      this.hotelZoneForm.get('City').setValue('');
      if(val){
        this.citySelection = false;
      }else {
        this.citySelection = true;
      }
      this.getHotelsByCity();
    }

    getHotelsByCity(check?){
      let cityVal =this.hotelZoneForm.get('City').value;
      let countryVal =this.hotelZoneForm.get('City').value;
      if(countryVal && cityVal){
        this.selectedHotelList = [];
        this.apiserv.Get(`/ActivityHotelZone/GetHotelByCityCode/${cityVal}`).subscribe(res => {
            if (res) {
             this.hotelList = res.data;
             this.hotelList.forEach(hotelDet=>{
              hotelDet['check'] = check ? this.editResp.hotels.includes(hotelDet.hotelId) :false;
             })
             this.selectedHotelCheck = new Array(res.data.length).fill(false);
            }
        });
      }else {
        this.hotelList = [];
      }
    }

    checkHotelSelection(hotelId){
      this.hotelList.forEach(hotelDet=>{
        if(hotelDet.hotelId === hotelId){
          hotelDet['check'] = !hotelDet['check'];
        }
      });
      if(this.hotelList.every(hotelDet=> hotelDet['check'] )){
        this.hotelZoneForm.get('selectAll').setValue(true);
      }else {
        this.hotelZoneForm.get('selectAll').setValue(false);
      }
    }

    SelectDeselectHotels(){
      let val = this.hotelZoneForm.get('selectAll').value;
      this.hotelList.forEach(hotelDet=>{
        hotelDet['check'] = val;
      });
    }

    saveUpdateHotelZone(){
      if(!this.hotelList.some(hotelDet=> hotelDet['check'] )){
        this.commonMasterSer.showMessage(false, 'Please select a hotel');
        return;
      }
      if(this.hotelZoneForm.status == "INVALID"){
         this.validServ.showValidationsMsg(this.hotelZoneForm);
        setTimeout(() => {
        this.validServ.scrollToError();
        }, 50);
      } else if(this.hotelZoneForm.status == "VALID"){
        let formVal = this.hotelZoneForm.getRawValue();
        let PostData = {
          HotelZoneId: this.Edit_Id ?? '',
          ZoneName: formVal.ZoneName,
          Country:formVal.Country,
          City:formVal.City,
          Hotels:'',
        };
        let hotel_arr = [];
        this.hotelList.forEach(hotelDet=>{
          if(hotelDet['check']){
            hotel_arr.push(hotelDet.hotelId);
          }
        })
        PostData.Hotels = hotel_arr.join(',');
        let url = this.Edit_Id ? `Update` : `Save`
        this.apiserv.Post(`/ActivityHotelZone/${url}`, PostData).subscribe(res=>{
          if(res){
            this.commonMasterSer.showMessage(res.status, res.message);
            this.BackButton();
          }
        })
      }
    }


  BackButton(){
    this.router.navigateByUrl(`ActivityConfiguration/HotelZone/Search`);
  }
}
