import { Component, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { FlightDetailDto } from 'src/app/core/models/flight-service/flight-contracts.model';
import { API } from 'src/app/core/services/api.service';
import { FlightContractService } from 'src/app/core/services/flight-contract.service.ts/flight-contract.service';

@Component({
  selector: 'app-edit-flight-details',
  templateUrl: './edit-flight-details.component.html',
})
export class EditFlightDetailsComponent implements OnInit {

  constructor(
    public _staticService: StaticDataService,
    public activateRoute: ActivatedRoute,
    public validationService: ValidationService,
    public _flightContractService: FlightContractService,
    private Fb: FormBuilder,
    public _commonService: CommonFunctionService,
    private ApiServ: API,
    public router: Router,
  ) { }
  ContractId;
  Formdata: FormGroup;
  ngOnInit(): void {
    this.PageSetUp();
  };
  Defaultdate = new Date();


  PageSetUp() {
    this.ContractId = this.activateRoute.snapshot.paramMap.get('ContractId');
    this.GetFlightContratByID();
  };

  FlightContractDetails;
  DatesListArray = []
  GetFlightContratByID() {
    this.ApiServ.Get('/FlightContract/GetFlightContractByID/' + this.ContractId).subscribe(res => {
      if (res) {
        this.FlightContractDetails = res.data;
        if (this.FlightContractDetails.departure_dates && this.FlightContractDetails.multi_day_operation_type == 'SPECIFICDATES') {
          let datelist = this.FlightContractDetails.departure_dates.split(',');
          if (datelist && datelist.length > 0) {
            this.DatesListArray = datelist.map(e => {
              let date = new Date(e)
              date.setHours(0, 0, 0, 0);
              return moment(date).format('YYYY-MM-DD')
            });
          }
        };
        if (this.FlightContractDetails?.operation_from && this.FlightContractDetails?.operation_to) {
          let from_date = new Date(this.FlightContractDetails.operation_from);
          let to_date = new Date(this.FlightContractDetails.operation_from);
          if (this.FlightContractDetails.departure_dates && this.FlightContractDetails.multi_day_operation_type == 'SPECIFICDATES') {
            let datelist = this.FlightContractDetails.departure_dates.split(',');
            let dates = [];
            datelist.forEach(e => {
              if (new Date(e) >= new Date()) dates.push(e)
            });
            from_date = new Date(dates[0]);
            to_date = new Date(datelist[datelist.length - 1]);
          }
          let current_date = new Date();
          from_date.setHours(0, 0, 0, 0);
          to_date.setHours(0, 0, 0, 0);
          current_date.setHours(0, 0, 0, 0);
          if (from_date.getTime() < current_date.getTime() && to_date.getTime() > current_date.getTime()) {
            this.Defaultdate = current_date;
          } else {
            this.Defaultdate = from_date;
          }
        }
        this.OnIntForm();
      }
    });
  };
  WeekDaysList = [];
  OnIntForm() {
    this.Formdata = this.Fb.group({
      Default: [''],
      is_multi_day: [false],
      outbond: this.Fb.array([]),
      inbond: this.Fb.array([]),
    });
    if (this.FlightContractDetails?.is_multi_day) {
      this.Formdata.addControl('date_type', this.validationService.required);
      this.Formdata.addControl('from_date', this.validationService.required);
      this.Formdata.addControl('to_date', this.validationService.required);
      if (this.FlightContractDetails.multi_day_operation_type == 'RANGE') {
        this._staticService.WeekDaysList.forEach(e => {
          if (this.FlightContractDetails?.departure_days?.includes(e.Itemkey2)) this.WeekDaysList.push(e.Itemkey2);
        })
        this.Formdata.addControl('days', this.Fb.control(''));
      };
    } else {
      this.Formdata.get('Default').setValue(this.FlightContractDetails.departure_date);
      this.GetFlightDetailsList();
    };
  };

  get outbond() {
    return this.Formdata.get('outbond') as FormArray;
  };
  get inbond() {
    return this.Formdata.get('inbond') as FormArray;
  };

  GetFlightDetailsList() {
    if (
      this.Formdata.get('date_type')?.invalid ||
      this.Formdata.get('from_date')?.invalid ||
      this.Formdata.get('to_date')?.invalid
    ) {
      this.validationService.showValidationsMsg(this.Formdata);
      setTimeout(() => {
        this.validationService.scrollToError();
      }, 50);
      return;
    }
    let value = this.Formdata.getRawValue();
    let requestObject = {
      contract_id: this.ContractId,
      date_type: value.date_type,
      from_date: '',
      to_date: '',
      days: '',
      flight_details: [],
    };
    if (this.FlightContractDetails?.is_multi_day) {
      requestObject.from_date = this._commonService.convertDateToSave(value.from_date);
      requestObject.to_date = this._commonService.convertDateToSave(value.to_date);
      requestObject.days = value.days ? value.days.join(',') : '';
    } else {
      requestObject.from_date = this._commonService.convertDateToSave(value.Default);
      requestObject.to_date = this._commonService.convertDateToSave(value.Default);
      const date = moment(value.Default);
      const dayName = date.format('dddd');
      requestObject.days = dayName;
    };
    this.ApiServ.Post('/FlightContract/GetAllFlightDetailsBySearch', requestObject).subscribe(res => {
      if (res) {
        if (res['status']) {
          this.FlightContractListBind(res.data)
        } else {
          this._commonService.showMessage(res['status'], res['message'])
        }
      }
    });
  };
  OutBondDate;
  InBondDate;
  DepartureDate;
  FlightContractListBind(legs) {
    this.outbond.clear();
    this.GetAllSelectedData(legs);
    let outbondlist = legs.filter(e => e.seg_nbr == 1).sort((a, b) => a.leg_nbr - b.leg_nbr);
    this.DepartureDate = outbondlist[0].departure_date;
    this.OutBondDate = this._commonService.convertDateToShow(outbondlist[0].departure_date);
    outbondlist.forEach((object, i) => {
      this.addFlightGroupBtn(true);
      this.outbond.controls[i].get('airline_code').setValue(object['airline_code']);
      this.outbond.controls[i].get('flight_no').setValue(object['flight_no']);
      this.outbond.controls[i].get('_aircraft_type').setValue(object['aircraft_type_id']);
      this.outbond.controls[i].get('from_airport').setValue(object['from_airport']);
      this.outbond.controls[i].get('to_airport').setValue(object['to_airport']);
      this.outbond.controls[i].get('departure_terminal').setValue(object['departure_terminal']);
      this.outbond.controls[i].get('is_next_day_arrival').setValue(object['is_next_day_arrival']);
      this.outbond.controls[i].get('arrival_terminal').setValue(object['arrival_terminal']);
      this.outbond.controls[i].get('is_next_day_departure').setValue(object['is_next_day_departure']);
      if (object['departure_time']) {
        let hour = object['departure_time'].split(':')[0];
        let minutes = object['departure_time'].split(':')[1];
        this.outbond.controls[i].get('departure_Hour').setValue(hour.length != 2 ? '0' + hour : hour)
        this.outbond.controls[i].get('departure_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
      }
      if (object['arrival_time']) {
        let hour = object['arrival_time'].split(':')[0];
        let minutes = object['arrival_time'].split(':')[1];
        this.outbond.controls[i].get('arrival_hour').setValue(hour.length != 2 ? '0' + hour : hour)
        this.outbond.controls[i].get('arrival_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
      }
      if (object['flying_duration']) {
        let hour = object['flying_duration'].split(':')[0];
        let minutes = object['flying_duration'].split(':')[1];
        this.outbond.controls[i].get('flying_duration_hour').setValue(hour.length != 2 ? '0' + hour : hour)
        this.outbond.controls[i].get('flying_duration_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
      }
    });
    let inbondlist = legs.filter(e => e.seg_nbr == 2);
    if (inbondlist && inbondlist.length > 0) {
      this.InBondDate = this._commonService.convertDateToShow(inbondlist[0].departure_date);
      inbondlist = inbondlist.sort((a, b) => a.leg_nbr - b.leg_nbr);
      inbondlist.forEach((object, i) => {
        this.addFlightGroupBtn(false);
        this.inbond.controls[i].get('airline_code').setValue(object['airline_code']);
        this.inbond.controls[i].get('flight_no').setValue(object['flight_no']);
        this.inbond.controls[i].get('_aircraft_type').setValue(object['aircraft_type_id']);
        this.inbond.controls[i].get('from_airport').setValue(object['from_airport']);
        this.inbond.controls[i].get('to_airport').setValue(object['to_airport']);
        this.inbond.controls[i].get('departure_terminal').setValue(object['departure_terminal']);
        this.inbond.controls[i].get('is_next_day_arrival').setValue(object['is_next_day_arrival']);
        this.inbond.controls[i].get('arrival_terminal').setValue(object['arrival_terminal']);
        this.inbond.controls[i].get('is_next_day_departure').setValue(object['is_next_day_departure']);
        if (object['departure_time']) {
          let hour = object['departure_time'].split(':')[0];
          let minutes = object['departure_time'].split(':')[1];
          this.inbond.controls[i].get('departure_Hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.inbond.controls[i].get('departure_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        }
        if (object['arrival_time']) {
          let hour = object['arrival_time'].split(':')[0];
          let minutes = object['arrival_time'].split(':')[1];
          this.inbond.controls[i].get('arrival_hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.inbond.controls[i].get('arrival_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        }
        if (object['flying_duration']) {
          let hour = object['flying_duration'].split(':')[0];
          let minutes = object['flying_duration'].split(':')[1];
          this.inbond.controls[i].get('flying_duration_hour').setValue(hour.length != 2 ? '0' + hour : hour)
          this.inbond.controls[i].get('flying_duration_minutes').setValue(minutes.length != 2 ? '0' + minutes : minutes)
        }
      });
    }
  };

  GetAllSelectedData(data) {
    let all_aircraft_type = data.map(e => e.aircraft_type_id);
    let AllAirline = data.map(e => e.airline_code);
    let AllAirports = [];
    data.forEach(e => {
      AllAirports.push(e.from_airport);
      AllAirports.push(e.to_airport);
    });
    if (all_aircraft_type.length > 0) this.GetAircraftTypeById(all_aircraft_type.join(','));
    if (AllAirports.length > 0) this.GetAirportsByAirportCode(AllAirports.join(','));
    if (AllAirline.length > 0) this.GetAirlineByAirlineCode(AllAirline.join(','));
  };

  addFlightGroupBtn(check) {
    let formgroup = check ? this.outbond : this.inbond
    formgroup.push(
      this.Fb.group({
        airline_code: this.validationService.required,
        flight_no: this.validationService.required,
        _aircraft_type: this.validationService.required,
        from_airport: [{ value: null, disabled: true }, Validators.required],
        to_airport: [{ value: null, disabled: true }, Validators.required],
        departure_Hour: this.validationService.required,
        departure_minutes: this.validationService.required,
        departure_terminal: [''],
        is_next_day_arrival: [{ value: false, disabled: true }],
        arrival_hour: this.validationService.required,
        arrival_minutes: this.validationService.required,
        arrival_terminal: [''],
        flying_duration_hour: this.validationService.required,
        flying_duration_minutes: this.validationService.required,
        is_next_day_departure: [{ value: false, disabled: true }],
      })
    );
  };
  UpdateControlsValidation(group, name, type) {
    if (type == 'add') {
      group.get(name)?.addValidators([Validators.required]);
      group.get(name)?.updateValueAndValidity();
    } else {
      group.get(name)?.clearValidators();
      group.get(name)?.updateValueAndValidity();
      group.get(name)?.markAsUntouched();
    };
  };

  Saveflightdetails() {
    if (this.Formdata.invalid) {
      this.validationService.showValidationsMsg(this.Formdata);
      setTimeout(() => {
        this.validationService.scrollToError();
      }, 50);
      return;
    }
    let value = this.Formdata.getRawValue();
    let requestObject = {
      contract_id: this.ContractId,
      date_type: value.date_type,
      from_date: '',
      to_date: '',
      days: '',
      flight_details: [],
    };
    if (this.FlightContractDetails?.is_multi_day) {
      requestObject.from_date = this._commonService.convertDateToSave(value.from_date);
      requestObject['to_date'] = this._commonService.convertDateToSave(value.to_date);
      requestObject.days = value.days ? value.days.join(',') : '';
    } else {
      requestObject.from_date = this._commonService.convertDateToSave(this.DepartureDate);
      requestObject.to_date = this._commonService.convertDateToSave(this.DepartureDate);
      const date = moment(this.DepartureDate);
      const dayName = date.format('dddd');
      requestObject.days = dayName;
    }
    value.outbond.forEach((e, i) => {
      let fligtDetlPostData = new FlightDetailDto();
      fligtDetlPostData.airline_code = e.airline_code
      fligtDetlPostData.flight_no = e.flight_no;
      fligtDetlPostData.aircraft_type_id = e._aircraft_type;
      fligtDetlPostData.from_airport = e.from_airport;
      fligtDetlPostData.to_airport = e.to_airport;
      fligtDetlPostData.departure_time = e.departure_Hour + ':' + e.departure_minutes + ':00';
      fligtDetlPostData.is_next_day_departure = e.is_next_day_departure;
      fligtDetlPostData.departure_terminal = e.departure_terminal;
      fligtDetlPostData.is_next_day_arrival = e.is_next_day_arrival;
      fligtDetlPostData.arrival_time = (e.arrival_hour || '00') + ':' + e.arrival_minutes + ':00';
      fligtDetlPostData.arrival_terminal = e.arrival_terminal;
      fligtDetlPostData.flying_duration = (e.flying_duration_hour || '00') + ':' + (e.flying_duration_minutes || '00') + ':00';
      fligtDetlPostData.leg_nbr = i + 1;
      fligtDetlPostData.seg_nbr = 1;
      requestObject.flight_details.push(fligtDetlPostData);
    });
    if (value.inbond && value.inbond.length > 0) {
      value.inbond.forEach((e, i) => {
        let fligtDetlPostData = new FlightDetailDto();
        fligtDetlPostData.airline_code = e.airline_code
        fligtDetlPostData.flight_no = e.flight_no;
        fligtDetlPostData.aircraft_type_id = e._aircraft_type;
        fligtDetlPostData.from_airport = e.from_airport;
        fligtDetlPostData.to_airport = e.to_airport;
        fligtDetlPostData.departure_time = e.departure_Hour + ':' + e.departure_minutes + ':00';
        fligtDetlPostData.is_next_day_departure = e.is_next_day_departure;
        fligtDetlPostData.departure_terminal = e.departure_terminal;
        fligtDetlPostData.is_next_day_arrival = e.is_next_day_arrival;
        fligtDetlPostData.arrival_time = (e.arrival_hour || '00') + ':' + e.arrival_minutes + ':00';
        fligtDetlPostData.arrival_terminal = e.arrival_terminal;
        fligtDetlPostData.flying_duration = (e.flying_duration_hour || '00') + ':' + (e.flying_duration_minutes || '00') + ':00';
        fligtDetlPostData.leg_nbr = i + 1;
        fligtDetlPostData.seg_nbr = 2;
        requestObject.flight_details.push(fligtDetlPostData);
      });
    }
    this.ApiServ.Post('/FlightContract/UpdateFlightDetails', requestObject).subscribe(res => {
      if (res) {
        this._commonService.showMessage(res['status'], res['message']);
        setTimeout(() => {
          if (res['status']) this.router.navigate(['/Services/FlightInventory/Search']);
        }, 500);
      }
    });
  };
  weekdaylist
  checkDateForHighlight(date) {
    if (!this.FlightContractDetails.is_multi_day) {
      return false; // If not multi-day event, don't highlight any date
    }
    let currentDate = new Date(date.year, date.month, date.day);
    currentDate.setHours(0, 0, 0, 0);
    if (this.FlightContractDetails?.multi_day_operation_type === 'RANGE') {
      let fromDate = new Date(this.FlightContractDetails.operation_from);
      let toDate = new Date(this.FlightContractDetails.operation_to);
      fromDate.setHours(0, 0, 0, 0);
      toDate.setHours(0, 0, 0, 0);
      if (currentDate < fromDate || currentDate > toDate) {
        return false; // currentDate is outside the range, don't highlight
      }
      return this.FlightContractDetails.departure_days.includes(currentDate.toLocaleDateString('en-US', { weekday: 'long' }));
    } else {
      return this.DatesListArray.some(e => e == moment(currentDate).format('YYYY-MM-DD'));
    }
  }

  @ViewChild('from_date') from_date;
  @ViewChild('to_date') to_date;
  onSelect(date, caleder) {
    if (date && !this.checkDateForHighlight(date)) {
      if (caleder == 'from_date') {
        this.from_date.overlayVisible = true;
        this.Formdata.get('from_date').setValue(null);
      } else {
        this.to_date.overlayVisible = true;
        this.Formdata.get('to_date').setValue(null);
      }
    };
  };

  ResetForm() {
    this.Formdata.reset();
  };

  GetAircraftTypeById(data) {
    let obj = {
      aircraft_type_id: data
    }
    this.ApiServ.Post('/MasterSearch/GetAircraftTypeById', obj).subscribe(res => {
      if (res) {
        this._flightContractService.AllAirCraftList = res.data;
        setTimeout(() => {
          this._flightContractService.AllAirCraftList = [];
        }, 500);
      }
    });
  };
  GetAirportsByAirportCode(data) {
    let obj = {
      airport_code: data
    }
    this.ApiServ.AdminGoPost('/Airport/GetAirportsByAirportCode', obj).subscribe(res => {
      if (res) {
        if (res.Result && res.Result.length > 0) {
          this._flightContractService.AirportList = res.Result;
          this._flightContractService.AirportList = this._flightContractService.AirportList.map(e => ({ 'ac': e.airport_code, 'ct': e.city_name }));
        }
        setTimeout(() => {
          this._flightContractService.AirportList = [];
        }, 500);
      }
    });
  };
  GetAirlineByAirlineCode(data) {
    let obj = {
      airline_code: data
    }
    this.ApiServ.AdminGoPost('/MasterSearch/GetAirlineByAirlineCode', obj).subscribe(res => {
      if (res) {
        this._flightContractService.AirlineList = res.Result;
        setTimeout(() => {
          this._flightContractService.AirlineList = [];
        }, 500);

      }
    });
  };
  public dateValidation(toDate): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (toDate && control.value < toDate) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  Update_Validation() {
    let from_date = this.Formdata.get('from_date').value;
    if (from_date) {
      this.Formdata.get("to_date").clearValidators();
      this.Formdata.get("to_date").setErrors(null);
      this.Formdata.get("to_date").addValidators(Validators.compose([Validators.required, this.dateValidation(from_date)]));
      this.Formdata.get("to_date").updateValueAndValidity();
    }
  }
  backClick() {
    this.router.navigateByUrl("Services/FlightInventory/Search");
  }
  selectAllDays() {
    const weekDays = this.WeekDaysList.map(day => day);
    this.Formdata.controls['days'].setValue(weekDays);
  };

  IsAllDaysSelected(): boolean {
    let alldays = this.WeekDaysList.every(e => {
      if (this.Formdata.controls['days']?.value && this.Formdata.controls['days']?.value.includes(e)) {
        return true
      }
      return false
    })
    return alldays
  }

  clearAllDays() {
    this.Formdata.controls['days'].setValue([]);
  }
}
