import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { API } from '../../../../../../core/services/api.service';
import { isSameDay, startOfYear, endOfYear, addDays, parseISO } from 'date-fns';
import { ValidationService } from '../../../../../../core/common/validation.service';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import moment from 'moment';
import { CommonFunctionService } from '../../../../../../core/common/common-function.service';
import { ManageHotelService } from '../../../../../../core/services/HotelServices/manage-hotel.service';

@Component({
  standalone: false,
  selector: 'app-update-minimum-stay',
  templateUrl: './update-minimum-stay.component.html',
})
export class UpdateMinimumStayComponent implements OnInit {
  Extranet_Hotel_Id;
  Edit_Id;
  GetAllContractResp;
  GetAllData;
  Defaultdate = new Date();
  selectedDate: Date | null = null;
  DisableDate;
  selectAll = ['Select All'];
  hasResult = false;
  AllSeason;
  enabledDates: Date[] = [];
  AllDaysArr = [
    {Key:'Mon',Value:'Monday'},
    {Key:'Tue',Value:'Tuesday'},
    {Key:'Wed',Value:'Wednesday'},
    {Key:'Thu',Value:'Thursday'},
    {Key:'Fri',Value:'Friday'},
    {Key:'Sat',Value:'Saturday'},
    {Key:'Sun',Value:'Sunday'}
  ];
  Minimum_stay_Search_Form:FormGroup;
  Minimum_stay_Save_Form:FormGroup;

  constructor(private activateRoute:ActivatedRoute,private apiserv:API,public validserv:ValidationService,public fb:FormBuilder,public commonMasterSer:CommonFunctionService,
    private hotelmanageserv:ManageHotelService,private router:Router) { }

  ngOnInit(): void {
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.Minimum_stay_Search_Form = this.fb.group({
      room_Name:'',
      room_Id:'',
      date_type:this.validserv.required,
      contract_days:''
    });
    this.GetAllSeason();
    this.GetById();
    // this.disabledDates();
  }

  GetById(){
    this.apiserv.Get('/ExtranetMinStay/GetExtranetRoomMinStayById/'+ this.Edit_Id).subscribe(res=>{
      if(res && res.data){
        // this.SetRoomdata(res.data);
        let dates_range_arr = res.data['date_ranges'] ? JSON.parse(res.data.date_ranges) : [];
        this.Minimum_stay_Search_Form.get('room_Name')?.setValue(res.data.room_name);
        this.Minimum_stay_Search_Form.get('room_Id')?.setValue(res.data.extranet_room_id);
        this.GetAllData = res.data;
        // this.GetAllData['max_adult_occupancy'] = 3;
        dates_range_arr.forEach(date_range=>{
          const startDate = parseISO(date_range.date_from);
          const endDate = parseISO(date_range.date_to);

          for (let d = startDate; d <= endDate; d = addDays(d, 1)) {
            this.enabledDates.push(d);
          }
        });
        this.enabledDates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
        for(let i=0;i<this.enabledDates.length;i++){
          if(new Date(this.enabledDates[i]).getTime() >= new Date().getTime()){
            this.Defaultdate = new Date(this.enabledDates[i]);
            break;
          }
          if(this.enabledDates.length -1 == i){
            this.Defaultdate = new Date(this.enabledDates[i]);
          }
        }
        let to_date = new Date(this.enabledDates[0]);
        to_date.setMonth(to_date.getMonth()-12)
        let from_date = new Date(this.enabledDates[0]);
        from_date.setMonth(from_date.getMonth() + 18)
        this.DisableDate = this.disabledDates(to_date,from_date)
      }
    })
  }
  disabledDates(to_date,From_date): Date[] {
    const start = startOfYear(new Date(to_date));
    const end = endOfYear(new Date(From_date));
    const disabledDates: Date[] = [];

    for (let d = start; d <= end; d.setDate(d.getDate() + 1)) {
      if (!this.isDateEnabled(new Date(d))) {
        disabledDates.push(new Date(d));
      }
    }
    
    return disabledDates;
  }

  isDateEnabled(date: Date): boolean {
    return this.enabledDates.some(enabledDate => 
      isSameDay(date, enabledDate)
    );
  }
  BackButton(){
    this.hotelmanageserv.Active_tab = 'MinimumStay';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  SearchAdultcontract(){
    if (this.Minimum_stay_Search_Form.status == "INVALID") {
      this.validserv.showValidationsMsg(this.Minimum_stay_Search_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let val = this.Minimum_stay_Search_Form.getRawValue();
    let ReqObj = {
      extranet_room_id:val.room_Id,
      date_range:[] as any[],
      extranet_hotel_id:this.Extranet_Hotel_Id,
      days:val.contract_days ? val.contract_days.join(','):'',
    }
    if(val.date_type == 'SPECIFICDATES'){
      const selectedFromDate = new Date(val.date[0]);
      const fromuserTimezoneOffset = selectedFromDate.getTimezoneOffset() * 60000; // Convert minutes to milliseconds
      const fromDate = new Date(selectedFromDate.getTime() - fromuserTimezoneOffset);
      const selectedToDate = new Date(val.date[1]);
      const toUserTimezoneOffset = selectedToDate.getTimezoneOffset() * 60000; // Convert minutes to milliseconds
      const toDate = new Date(selectedToDate.getTime() - toUserTimezoneOffset);
      ReqObj.date_range.push({
        date_from:fromDate,
        date_to:toDate,
      });
    }else if(val.date_type == 'SEASON'){
      val.Season_Id.forEach(data => {
        let matched_season_by_id = this.AllSeason.find(e => e.extranet_season_id == data);
        if (matched_season_by_id) {
          if (typeof (matched_season_by_id['date_range']) == 'string') {
            let splited_date = matched_season_by_id.date_range.split(', ');
            splited_date.forEach((z) => {
              ReqObj.date_range.push({
                date_from: new Date(`${z.split(' - ')[0]}T00:00:00.000Z`),
                date_to:new Date(`${z.split(' - ')[1]}T00:00:00.000Z`),
              });
            })
          }
        }
      })
    }
    this.apiserv.Post('/ExtranetMinStay/GetUpdateMinStay',ReqObj).subscribe(resp=>{
      this.hasResult = true;
      if(resp){
        this.GetAllContractResp = resp.data;
          this.Minimum_stay_Save_Form = this.fb.group({
            Copy_Group:this.fb.group({
              min_stay:'',      
            }),
            Adult_Contract_Arr:this.fb.array([])
          });
        let contract_group = this.Minimum_stay_Save_Form.controls['Copy_Group'] as FormGroup;
        // for(let i=1;i<=this.GetAllData['max_adult_occupancy'];i++){
        //   contract_group.addControl(`adult_${i}`,new FormControl(''));
        // }
       if(resp.data){
        resp.data.sort((a,b)=>{
          let from_date = new Date(a.contract_date);
          let to_date = new Date(b.contract_date)
          return from_date.getTime() - to_date.getTime() 
        })
        resp.data.forEach((contractc_data,ind)=>{
          let formArray = this.Minimum_stay_Save_Form.controls['Adult_Contract_Arr'] as FormArray;
          let day  = this.AllDaysArr.find(e=>e.Value == contractc_data.minstay_day)
          formArray.push(this.fb.group({
            min_stay:this.fb.control(contractc_data.min_stay,this.validserv.required),
            contract_date:contractc_data.date,
            extranet_room_id:contractc_data.extranet_room_id,
            contract_day:day ? day.Key : '',
            extranet_contract_rate_id:contractc_data.extranet_room_min_stay_id,
          }));
          // for(let i=1;i<=this.GetAllData['max_adult_occupancy'];i++){
          //   let formgroup = formArray.controls[ind] as FormGroup;
          //   formgroup.addControl(`adult_${i}`,new FormControl(contractc_data[`adult_${i}`]));
          // }
        })
       }else {
        this.commonMasterSer.showMessage(resp.status,resp.message);
       }
      }
    })
  }
  copycolumn(colname,controlval?){
    let value = controlval ? controlval : this.Minimum_stay_Save_Form.controls['Adult_Contract_Arr']['controls'][0].get(colname).value;
    if(this.GetAllContractResp && this.GetAllContractResp.length > 0){
      for(let i = 0;i<this.GetAllContractResp.length;i++){
          this.Minimum_stay_Save_Form.controls['Adult_Contract_Arr']['controls'][i].get(colname).setValue(value);
      }
    }
  }
  CopyOnUi(){
    let val = this.Minimum_stay_Save_Form.controls['Copy_Group'].getRawValue();
    if(val.min_stay){
      this.copycolumn('min_stay',val.min_stay);
    }
    // for(let i=1;i<=this.GetAllData['max_adult_occupancy'];i++){
    //   if(val[`adult_${i}`]){
    //     this.copycolumn(`adult_${i}`,val[`adult_${i}`]);
    //   }
    // }
  }
  Save(){
    if (this.Minimum_stay_Save_Form.status == "INVALID") {
      this.validserv.showValidationsMsg(this.Minimum_stay_Save_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let val = this.Minimum_stay_Save_Form.controls['Adult_Contract_Arr'].getRawValue();
    let reqObjArr: any[] = [];
    val.forEach(adultcontract=>{
      reqObjArr.push({
        extranet_room_min_stay_id : adultcontract.extranet_contract_rate_id,
        extranet_room_id : adultcontract.extranet_room_id,
        date : adultcontract.contract_date,
        minstay_day : adultcontract.contract_day,
        min_stay : adultcontract.min_stay ? adultcontract.min_stay :''
      })
    });
    this.apiserv.Post('/ExtranetMinStay/UpdateExtranetMinStay',reqObjArr).subscribe(resp=>{
      if(resp){
        this.commonMasterSer.showMessage(resp.status,resp.message);
        resp.status ? this.BackButton() : '';
      }
    })
  }
  Reset(){
    this.Minimum_stay_Search_Form.reset();
  }
  Check_day_type(){
    let daysArr = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];
    let value = this.Minimum_stay_Search_Form.get('contract_days')?.value;
    if(value && value.length > 0 && (value.includes('Select All') || value.length == 7)){
      this.Minimum_stay_Search_Form.get('contract_days')?.setValue(daysArr);
      this.selectAll = []
    }else {
      this.selectAll = ['Select All']
    }
  }

  ShowDateTypeFields(event){
    if(event == 'SPECIFICDATES'){
      this.Minimum_stay_Search_Form.addControl('date', new FormControl('', Validators.compose([Validators.required, this.dateValidation()])));
      this.Minimum_stay_Search_Form.removeControl('Season_Id');
    }else if(event == 'SEASON'){
      this.Minimum_stay_Search_Form.addControl('Season_Id',new FormControl('',Validators.required))
      this.Minimum_stay_Search_Form.removeControl('date');
    }else {
      this.Minimum_stay_Search_Form.removeControl('Season_Id');
      this.Minimum_stay_Search_Form.removeControl('date');
    }
  }
  public dateValidation(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (control.value.length <= 1 || control.value[1] == null) {
          return { 'todate': true };
        }
      }
      return null;
    };
  }

  GetAllSeason(){
    let ReqObj = {
      season_name:'',
      hotel_id:this.Extranet_Hotel_Id
    }
    this.apiserv.Post('/ExtranetSeason/GetAllExtranetSeason',ReqObj).subscribe(res=>{
      if(res){
        this.AllSeason = res.data;
      }
    })
  }
}
