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

@Component({
  selector: 'hotel-update-adult',
  templateUrl: './hotel-update-adult.component.html',
})
export class HotelUpdateAdultComponent implements OnInit {
  Extranet_Hotel_Id;
  Edit_Id;
  GetAllContractResp;
  GetAllData;
  AllSeason;
  Defaultdate = new Date();
  selectedDate: Date | null = null;
  DisableDate;
  selectAll = ['Select All'];
  hasResult = false;
  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'}
  ];
  Adult_contract_Search_Form:FormGroup;
  Adult_contract_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.Adult_contract_Search_Form = this.fb.group({
      room_Name:'',
      rate_Plan:'',
      meal_Plan:'',
      currency:'',
      contract_days:'',
      date_type:this.validserv.required,
    })
    this.GetAllSeason();
    this.GetById();
    // this.disabledDates();
  }

  GetById(){
    this.apiserv.Get('/ExtranetRoomContract/GetExtranetRoomContractById/'+ this.Edit_Id).subscribe(res=>{
      if(res && res.data){
        // this.SetRoomdata(res.data);
        let dates_range_arr = res.data['contract_dates'] ? JSON.parse(res.data.contract_dates) : [];
        this.Adult_contract_Search_Form.get('room_Name').setValue(res.data.room_name);
        this.Adult_contract_Search_Form.get('rate_Plan').setValue(res.data.rate_plan_name);
        this.Adult_contract_Search_Form.get('meal_Plan').setValue(res.data.meal_plan_name);
        this.Adult_contract_Search_Form.get('currency').setValue(res.data.currency_code);
        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 = 'RoomContract';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  SearchAdultcontract(){
    if (this.Adult_contract_Search_Form.status == "INVALID") {
      this.validserv.showValidationsMsg(this.Adult_contract_Search_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let date_arr = [];
    let val = this.Adult_contract_Search_Form.getRawValue();
    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);
      date_arr.push({
        date_from:fromDate,
        date_to:toDate,
      });
    }else if(val.date_type == 'SEASON'){
      let season_id = val.Season_Id
      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) => {
              date_arr.push({
                date_from: new Date(`${z.split(' - ')[0]}T00:00:00.000Z`),
                date_to:new Date(`${z.split(' - ')[1]}T00:00:00.000Z`),
              });
            })
          }
        }
      })
    }
    let ReqObj = {
      extranet_contract_id:this.Edit_Id,
      date_range:date_arr,
      contract_days:val.contract_days ? val.contract_days.join(','):'',
    }
    
    this.apiserv.Post('/ExtranetRoomContract/GetAllAdultRateContract',ReqObj).subscribe(resp=>{
      this.hasResult = true;
      if(resp){
        this.GetAllContractResp = resp.data;
          this.Adult_contract_Save_Form = this.fb.group({
            Copy_Group:this.fb.group({}),
            Adult_Contract_Arr:this.fb.array([])
          });
        let contract_group = this.Adult_contract_Save_Form.controls['Copy_Group'] as FormGroup;
        let adult_extrabed_details = this.GetAllData['adult_extrabed_details_json'] ? JSON.parse(this.GetAllData['adult_extrabed_details_json']) : '';
        for(let i=1;i<=this.GetAllData['max_adult_occupancy'];i++){
          contract_group.addControl(`adult_${i}`,new FormControl(''));
          contract_group.addControl(`supplement_${i}`,new FormControl({value : adult_extrabed_details ? adult_extrabed_details[`adult_${i}`] : false, disabled : true}));
        }
       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.Adult_contract_Save_Form.controls['Adult_Contract_Arr'] as FormArray;
          let day  = this.AllDaysArr.find(e=>e.Value == contractc_data.contract_day)
          formArray.push(this.fb.group({
            contract_date:contractc_data.contract_date,
            contract_day:day ? day.Key : '',
            extranet_contract_rate_id:contractc_data.extranet_contract_rate_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.Adult_contract_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.Adult_contract_Save_Form.controls['Adult_Contract_Arr']['controls'][i].get(colname).setValue(value);
      }
    }
  }
  CopyOnUi(){
    let val = this.Adult_contract_Save_Form.controls['Copy_Group'].getRawValue();
    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.Adult_contract_Save_Form.status == "INVALID") {
      this.validserv.showValidationsMsg(this.Adult_contract_Save_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let val = this.Adult_contract_Save_Form.controls['Adult_Contract_Arr'].getRawValue();
    let reqObjArr = [];
    val.forEach(adultcontract=>{
      reqObjArr.push({
        extranet_contract_rate_id : adultcontract.extranet_contract_rate_id,
        extranet_contract_id : this.Edit_Id,
        contract_date : adultcontract.contract_date,
        contract_day : adultcontract.contract_day,
        adult_1 : adultcontract.adult_1 ? parseFloat(adultcontract.adult_1) : 0,
        adult_2 : adultcontract.adult_2 ? parseFloat(adultcontract.adult_2) : 0,
        adult_3 : adultcontract.adult_3 ? parseFloat(adultcontract.adult_3) : 0,
        adult_4 : adultcontract.adult_4 ? parseFloat(adultcontract.adult_4) : 0,
        adult_5 : adultcontract.adult_5 ? parseFloat(adultcontract.adult_5) : 0,
        adult_6 : adultcontract.adult_6 ? parseFloat(adultcontract.adult_6) : 0,
        adult_7 : adultcontract.adult_7 ? parseFloat(adultcontract.adult_7) : 0,
        adult_8 : adultcontract.adult_8 ? parseFloat(adultcontract.adult_8) : 0,
        adult_9 : adultcontract.adult_9 ? parseFloat(adultcontract.adult_9) : 0,
      })
    });
    this.apiserv.Post('/ExtranetRoomContract/UpdateExtranetAdultRate',reqObjArr).subscribe(resp=>{
      if(resp){
        this.commonMasterSer.showMessage(resp.status,resp.message);
        resp.status ? this.BackButton() : '';
      }
    })
  }
  Reset(){
    this.Adult_contract_Search_Form.reset();
  }
  Check_day_type(){
    let daysArr = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];
    let value = this.Adult_contract_Search_Form.get('contract_days').value;
    if(value && value.length > 0 && (value.includes('Select All') || value.length == 7)){
      this.Adult_contract_Search_Form.get('contract_days').setValue(daysArr);
      this.selectAll = []
    }else {
      this.selectAll = ['Select All']
    }
  }

  ShowDateTypeFields(event){
    if(event == 'SPECIFICDATES'){
      this.Adult_contract_Search_Form.addControl('date', new FormControl('', Validators.compose([Validators.required, this.dateValidation()])));
      this.Adult_contract_Search_Form.removeControl('Season_Id');
    }else if(event == 'SEASON'){
      this.Adult_contract_Search_Form.addControl('Season_Id',new FormControl('',Validators.required))
      this.Adult_contract_Search_Form.removeControl('date');
    }else {
      this.Adult_contract_Search_Form.removeControl('Season_Id');
      this.Adult_contract_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;
      }
    })
  }
}
