import { DatePipe, NgFor, NgIf, NgSwitch, NgSwitchCase } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { IonDatetime, 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';

@Component({
  selector: 'app-vihar-info',
  templateUrl: './vihar-info.page.html',
  styleUrls: ['./vihar-info.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgSwitch, NgSwitchCase, NgIf, NgFor, DatePipe]
})
export class ViharInfoPage implements OnInit {
  @ViewChild(IonDatetime, { static: true }) datetime: IonDatetime;
  santId = '1';
  upcomingPageNumber = 1;
  upcomingTotalPage = 1;
  upcomingViharList = [];
  pastPageNumber = 1;
  pastTotalPage = 1;
  pastViharList = [];
  viharId = '';
  isPastVihar = 'upcoming';
  noUpcomingFlag: boolean;
  noPastFlag: boolean;
  thanaMemberCount: string;
  constructor(
    private httpRequestService: HttpRequestService,
    private activatedRoute: ActivatedRoute,
    private stateManagementService: StateManagementService,
    private navCtrl: NavController,
    private router: Router,
    private utilityService: UtilityService
  ) { }

  ngOnInit() {
    this.thanaMemberCount = this.router.getCurrentNavigation().extras.state?.thanaMemberCount;
    this.santId = this.activatedRoute.snapshot.paramMap.get('santId');
  }

  ionViewWillEnter() {
    this.upcomingPageNumber = 1;
    this.upcomingTotalPage = 1;
    this.upcomingViharList = [];
    this.pastPageNumber = 1;
    this.pastTotalPage = 1;
    this.pastViharList = [];
    this.getUpcomingViharList(false, '');
    this.getPastViharList(false, '');
  }

  loadUpcomingData($event) {
    this.getUpcomingViharList(true, $event);
  }

  getUpcomingViharList(isFirstLoad, event) {
    if (this.upcomingPageNumber <= this.upcomingTotalPage) {
      this.httpRequestService.get(api.viharList, {
        sant_id: this.santId,
        page: this.upcomingPageNumber
      }).then((res: any) => {
        this.upcomingTotalPage = res.data.last_page;
        this.noUpcomingFlag = true;
        this.upcomingViharList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.upcomingPageNumber++;
      });
    } else {
      event.target.complete();
    }
  }

  loadPastData($event) {
    this.getPastViharList(true, $event);
  }

  getPastViharList(isFirstLoad, event) {
    if (this.pastPageNumber <= this.pastTotalPage) {
      this.httpRequestService.get(api.pastViharList, {
        sant_id: this.santId,
        page: this.pastPageNumber
      }).then((res: any) => {
        this.pastTotalPage = res.data.last_page;
        this.noPastFlag = true;
        this.pastViharList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pastPageNumber++;
      });
    } else {
      event.target.complete();
    }
  }

  isStarted(date, time): boolean {
    const fullDate = new Date(date);
    fullDate.setHours(time.slice(0, 2), time.slice(3, 5));
    return fullDate.toISOString() <= new Date().toISOString();
  }

  onAddVihar() {
    const componentProps = {
      viharFromPlace: '',
      viharToPlace: '',
      startDate: '',
      endDate: '',
      startTime: '05:00',
      isUpdate: false,
      santId: this.santId,
      from_latitude: '',
      from_longitude: '',
      to_latitude: '',
      to_longitude: '',
      thanaMemberCount: this.thanaMemberCount,
      to_sangh_id: null,
      from_sangh_id: null
    };
    this.stateManagementService.viharInfo = componentProps;
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.viharModal);
  }

  onUpdateVihar(vihar) {
    this.viharId = vihar.id;
    const componentProps = {
      viharFromPlace: vihar.from,
      viharToPlace: vihar.to,
      startDate: vihar.start_date,
      endDate: vihar.end_date,
      startTime: vihar.start_time,
      isUpdate: true,
      santId: this.santId,
      viharId: this.viharId,
      from_latitude: vihar.from_latitude,
      from_longitude: vihar.from_longitude,
      to_latitude: vihar.to_latitude,
      to_longitude: vihar.to_longitude,
      thanaMemberCount: this.thanaMemberCount,
      to_sangh_id: vihar.to_sangh_id,
      from_sangh_id: vihar.from_sangh_id
    };
    this.stateManagementService.viharInfo = componentProps;
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.viharModal);
  }

  formatAMPM(date) {
    let hours = date.slice(0, 2);
    const minutes = date.slice(3, 5);
    const ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12;
    const strTime = hours + ':' + minutes + ' ' + ampm;
    return strTime;
  }

  makeCall(contactNumber) {
    window.open('tel:' + contactNumber);
  }

  async deleteVihaar(vihaarData: any, index: number) {
    const isYes = await this.utilityService.presentConfirm(
      'Vihaar will be deleted for all Thanas',
      'Cancel', 'Confirm', 'Delete Vihaar'
    );
    if (isYes) {
      this.httpRequestService.delete(api.deleteVihaar.replace('{id}', String(vihaarData.id)))
        .then(() => {
          this.upcomingViharList.splice(index, 1);
        });
    }
  }

  address(element, type) {
    if (type === 'from') {
      this.utilityService.openGoogleMap(element.from_latitude, element.from_longitude);
    } else if (type === 'to') {
      this.utilityService.openGoogleMap(element.to_latitude, element.to_longitude);
    }
  }
}
