import { DatePipe, NgFor, NgIf, NgTemplateOutlet, TitleCasePipe } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { IonicSelectableItemTemplateDirective } from '@components/ionic-selectable/ionic-selectable-item-template.directive';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { GjDatetimeDirective } from '@directives/gj-datetime.directive';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { IdName, SanghData } from '@interfaces/common';
import { ViharInfoForm } from '@interfaces/form';
import { AlertController, IonicModule, NavController } from '@ionic/angular';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
import { format, parseISO } from 'date-fns';

enum ADDRESS_TYPE {
  Location = 1,
  Sangh = 2
}

@Component({
  selector: 'app-vihar-modal',
  templateUrl: './vihar-modal.page.html',
  styleUrls: ['./vihar-modal.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, ReactiveFormsModule, NgTemplateOutlet, NgIf, GjDatetimeDirective, NgFor, TitleCasePipe,
    DatePipe, IonicSelectableComponent, IonicSelectableItemTemplateDirective]
})
export class ViharModalPage implements OnInit {
  @ViewChild('fromLocation') fromLocation: ElementRef;
  @ViewChild('toLocation') toLocation: ElementRef;
  @ViewChild('sanghListComponent') sanghListComponent: IonicSelectableComponent;
  viharInfoForm: FormGroup<ViharInfoForm>;
  title: string;
  currentDate = this.formatDate((new Date()).toISOString());
  currentTime: string;
  nextDate: string;
  startTime: string;
  thanaFlag: boolean;
  pageNumber = 1;
  totalPage = 1;
  thanaList: any[] = [];
  firstConfirmationFlag = false;
  secondConfirmationFlag = false;
  startDateValue = '';
  fromLatitude: string;
  fromLongitude: string;
  toLatitude: string;
  toLongitude: string;
  fromAddressType: ADDRESS_TYPE = ADDRESS_TYPE.Sangh;
  toAddressType: ADDRESS_TYPE = ADDRESS_TYPE.Sangh;
  sanghList: Array<SanghData> = [];
  fromSelectedSangh: IdName = null;
  toSelectedSangh: IdName = null;
  sanghPageNumber = 1;
  sanghTotalPages = 1;
  sanghSearchText = '';
  prevValue: string;

  constructor(
    public stateManagementService: StateManagementService,
    private httpRequestService: HttpRequestService,
    private navCtrl: NavController,
    public alertController: AlertController,
    public utilityService: UtilityService
  ) { }

  ngOnInit() {
    this.nextDate = this.formatDate(new Date((new Date()).setDate((new Date()).getDate() + 15)).toISOString());
    this.title = this.stateManagementService?.viharInfo?.isUpdate ? 'Update' : 'Add';
    this.currentTime = `2012-12-15T${this.stateManagementService?.viharInfo?.startTime}:20.789`;
    this.startTime = this.formatTime(this.currentTime);
    this.startDateValue = this.stateManagementService?.viharInfo?.startDate;
    this.fromLatitude = this.stateManagementService?.viharInfo?.from_latitude;
    this.fromLongitude = this.stateManagementService?.viharInfo?.from_longitude;
    this.toLatitude = this.stateManagementService?.viharInfo?.to_latitude;
    this.toLongitude = this.stateManagementService?.viharInfo?.to_longitude;
    this.viharInfoForm = new FormGroup<ViharInfoForm>({
      viharFromPlace: new FormControl(this.stateManagementService?.viharInfo?.viharFromPlace, Validators.required),
      viharToPlace: new FormControl(this.stateManagementService?.viharInfo?.viharToPlace, Validators.required),
      startDate: new FormControl(this.stateManagementService?.viharInfo?.startDate || null, Validators.required),
      startTime: new FormControl(this.currentTime, Validators.required),
    });

    if (this.stateManagementService?.viharInfo?.from_sangh_id) {
      this.fromAddressType = ADDRESS_TYPE.Sangh;
      this.fromSelectedSangh = {
        id: this.stateManagementService?.viharInfo?.from_sangh_id,
        name: this.stateManagementService?.viharInfo?.viharFromPlace,
      };
      this.viharInfoForm.controls.viharFromPlace.setValue(this.fromSelectedSangh.name);
    }
    if (this.stateManagementService?.viharInfo?.to_sangh_id) {
      this.toAddressType = ADDRESS_TYPE.Sangh;
      this.toSelectedSangh = {
        id: this.stateManagementService?.viharInfo?.to_sangh_id,
        name: this.stateManagementService?.viharInfo?.viharToPlace,
      };
      this.viharInfoForm.controls.viharToPlace.setValue(this.toSelectedSangh.name);
    }
    this.getThanaList(false, '');
  }

  formatDate(value) {
    return format(parseISO(value), 'yyyy-MM-dd');
  }

  formatTime(value) {
    return format(parseISO(value), 'hh:mm a');
  }

  formatFullTime(value) {
    return format(parseISO(value), 'HH:mm');
  }

  initAutocompleteStartPlace(): void {
    this.utilityService.createAutocomplete(this.fromLocation.nativeElement).subscribe((details) => {
      this.viharInfoForm.controls.viharFromPlace.setValue(this.fromLocation.nativeElement.value);
      this.fromLatitude = details.geometry.location.lat();
      this.fromLongitude = details.geometry.location.lng();
    });
  }

  removeLatAndLongStartPlace() {
    this.fromLatitude = '';
    this.fromLongitude = '';
  }

  initAutocompleteEndPlace(): void {
    this.utilityService.createAutocomplete(this.toLocation.nativeElement).subscribe((details) => {
      this.viharInfoForm.controls.viharToPlace.setValue(this.toLocation.nativeElement.value);
      this.toLatitude = details.geometry.location.lat();
      this.toLongitude = details.geometry.location.lng();
    });
  }

  removeLatAndLongEndPlace() {
    this.toLatitude = '';
    this.toLongitude = '';
  }

  async submitData(form) {
    this.viharInfoForm.markAllAsTouched();
    if (this.viharInfoForm.invalid) { return; }

    const formData = new FormData();
    formData.append('from', form.value.viharFromPlace);
    formData.append('to', form.value.viharToPlace);
    formData.append('start_date', this.formatDate(new Date(form?.value?.startDate).toISOString()));
    formData.append('start_time', this.formatFullTime(form?.value?.startTime));
    formData.append('sant_id', this.stateManagementService?.viharInfo?.santId);
    formData.append('from_latitude', this.fromLatitude);
    formData.append('from_longitude', this.fromLongitude);
    formData.append('to_latitude', this.toLatitude);
    formData.append('to_longitude', this.toLongitude);
    if (this.fromAddressType === ADDRESS_TYPE.Sangh) {
      formData.append('from_sangh_id', this.fromSelectedSangh.id.toString());
    }
    if (this.toAddressType === ADDRESS_TYPE.Sangh) {
      formData.append('to_sangh_id', this.toSelectedSangh.id.toString());
    }

    if (this.stateManagementService?.viharInfo?.isUpdate) {
      this.updateVihar(formData);
    } else {
      this.addVihar(formData);
    }
  }

  addVihar(params) {
    this.presentAlertPrompt('add', params);
  }

  updateVihar(params) {
    this.presentAlertPrompt('update', params);
  }

  getThanaList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.post(api.santThanaList, {
        sant_id: Number(this.stateManagementService?.viharInfo?.santId),
        page: this.pageNumber
      }).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.thanaList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      });
    } else {
      event.target.complete();
    }
  }

  moveToVihar() {
    this.navCtrl.navigateBack(
      Roots.page + '/' +
      Roots.viharInfo.replace(':santId', String(this.stateManagementService?.viharInfo?.santId))
    );
  }

  ionViewWillEnter() {
    this.getSanghList();
  }

  ionViewWillLeave() {
    this.viharInfoForm.reset();
  }

  async presentAlert() {
    const message = +this.stateManagementService.viharInfo.thanaMemberCount > 0 ?
      `Thank you for submitting vihaar, On completion of vihaar.
      you will be awarded karmā points. <span>Vihar will be applicable to all Thana(s).</span>` :
      `Thank you for submitting vihaar, On completion of vihaar.
        you will be awarded karmā points`;
    const alert = await this.alertController.create({
      cssClass: 'vihar-approval',
      backdropDismiss: false,
      message,
      buttons: [{
        text: 'Ok',
        handler: () => {
          this.moveToVihar();
        }
      }]
    });
    await alert.present();
  }

  async presentAlertPrompt(type: string, params) {
    const alert = await this.alertController.create({
      mode: 'ios',
      cssClass: 'add-edit-vihar-alert',
      header: 'Confirm',
      subHeader: 'Are you sure that all information is correct?',
      message: 'Vihaar will be applicable to all Thana\'s',
      buttons: [
        {
          text: 'Yes',
          handler: () => {
            if (type === 'add') {
              if (!(this.firstConfirmationFlag && this.secondConfirmationFlag)) {
                return;
              }
              this.httpRequestService.post(api.addVihar, params).then(() => {
                this.presentAlert();
              });
            } else if (type === 'update') {
              if (!(this.firstConfirmationFlag && this.secondConfirmationFlag)) {
                return;
              }
              this.httpRequestService.post(
                api.updateVihar + '/' + this.stateManagementService?.viharInfo?.viharId, params
              )
                .then(() => {
                  this.moveToVihar();
                });
            }
          }
        }, {
          text: 'No',
          role: 'cancel',
          cssClass: 'secondary',
        }
      ]
    });

    await alert.present();
  }

  searchSangh(event: { component: IonicSelectableComponent; text: string }) {
    this.sanghSearchText = event.text;
    const isSameStr = this.utilityService.isSameStr(this.sanghSearchText, this.prevValue);
    this.prevValue = this.sanghSearchText;
    if (!isSameStr) {
      this.sanghPageNumber = 1;
      this.sanghList = [];
      event.component.showLoading();
      this.getSanghList().then(() => {
        event.component.hideLoading();
      });
    }
  }

  getSanghList() {
    return this.httpRequestService.get(api.sanghSearchList, {
      name: this.sanghSearchText.trim(),
      page: this.sanghPageNumber,
      limit: 15
    }).then((res: any) => {
      this.sanghList.push(...res.data.data);
      this.sanghTotalPages = res.data.last_page;
    });
  }

  addSangh(sangh, type: 'from' | 'to') {
    if (type === 'from') {
      this.fromSelectedSangh = {
        id: sangh.value.id,
        name: sangh.value.name
      };
      this.viharInfoForm.controls.viharFromPlace.setValue(sangh.value.name);
    } else {
      this.toSelectedSangh = {
        id: sangh.value.id,
        name: sangh.value.name
      };
      this.viharInfoForm.controls.viharToPlace.setValue(sangh.value.name);
    }
    this.sanghList = [];
    this.sanghListComponent.searchText = '';
    this.sanghSearchText = '';
    this.sanghPageNumber = 1;
    this.getSanghList();
  }

  updateAddressType(event, type: 'from' | 'to') {
    if (type === 'from') {
      this.viharInfoForm.controls.viharFromPlace.setValue('');
      this.fromAddressType = event.detail.value;
      this.fromSelectedSangh = null;
    } else {
      this.viharInfoForm.controls.viharToPlace.setValue('');
      this.toAddressType = event.detail.value;
      this.toSelectedSangh = null;
    }
  }

  getMoreSangh(event: { component: IonicSelectableComponent; text: string }) {
    if (this.sanghPageNumber >= this.sanghTotalPages) {
      event.component.disableInfiniteScroll();
      return;
    }
    this.sanghPageNumber++;
    this.getSanghList().then(() => {
      event.component.endInfiniteScroll();
    });
  }
}
