import { NgFor, NgIf } from '@angular/common';
import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { Message } from '@interfaces/common';
import { IonicModule, NavController } from '@ionic/angular';
import { LocalDatePipe } from '@pipes/local-date.pipe';
import { MessageTimePipe } from '@pipes/message-time.pipe';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-message',
  templateUrl: './message.page.html',
  styleUrls: ['./message.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgIf, NgFor, LocalDatePipe, MessageTimePipe]
})
export class MessagePage implements OnInit, OnDestroy {
  messages: Array<Message> = [];
  page = 1;
  total = 0;
  loader: boolean;
  destroy$: Subject<boolean> = new Subject<boolean>();
  days: Array<string> = ['Son', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  messageDateArr: Array<string> = [];
  searchValue: string;
  prevValue: string;

  constructor(
    private httpService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    private changeRef: ChangeDetectorRef,
    private ngZone: NgZone,
    private utilityService: UtilityService
  ) { }

  ngOnInit() {
    this.fetchMessages();
    this.stateManagementService.messageObservable.pipe(
      takeUntil(this.destroy$)
    ).subscribe((res: Message) => {
      this.messages = this.messages.filter((m) => +m.user_id !== +res.user_id);
      this.messages.unshift(res);
      this.changeRef.detectChanges();
    });
    this.stateManagementService.messageClearObservable.pipe(
      takeUntil(this.destroy$)
    ).subscribe((userId: number) => {
      this.messages.forEach(m => {
        if (m.user_id === userId) {
          m.message = null;
        }
      });
      this.changeRef.detectChanges();
    });
    this.stateManagementService.messageThreadRemoveObservable.pipe(
      takeUntil(this.destroy$)
    ).subscribe((userId: number) => {
      this.messages = this.messages.filter((m) => m.user_id !== userId);
      this.changeRef.detectChanges();
    });
    this.stateManagementService.generalData.unread_message_count = 0;
    this.stateManagementService.pushNotyObservable.next(this.stateManagementService.generalData);
  }


  searchConversion(searchValue) {
    this.searchValue = searchValue;
    const isSameStr = this.utilityService.isSameStr(this.searchValue, this.prevValue);
    this.prevValue = this.searchValue;
    if (!isSameStr) {
      this.page = 1;
      this.messages = [];
      this.fetchMessages();
    }
  }

  loadData(event) {
    if (this.messages.length === 0 || this.messages.length === this.total) {
      event.target.disabled = true;
      return;
    }
    this.page++;
    this.fetchMessages().then(() => {
      event.target.complete();
    });
  }

  fetchMessages(loader = true) {
    if (this.page === 1 && loader) {
      this.loader = true;
    }
    return new Promise((resolve, reject) => {
      const params = {
        name: this.searchValue,
        page: this.page
      };
      this.httpService.get(api.messageThread, params)
        .then((res: any) => {
          this.loader = false;
          res.data.data.forEach(message => {
            const dtString = this.formatDate(message);
            if (!this.messageDateArr.includes(dtString)) {
              this.messageDateArr.push(dtString);
            }
          });
          this.messages = this.messages.concat(res.data.data);
          this.total = res.data.total;
          resolve(true);
        }, (error) => {
          this.loader = false;
          this.alert.showToaster(error.error.message);
          reject(false);
        });
    });
  }

  goToDetail(item: {
    id: number;
    user_id: string | number;
    name: string;
    unread_count: number;
  }) {
    item.unread_count = 0;
    const params = {
      id: null,
      userId: null,
      name: item.name
    };
    if (item.user_id) {
      params.userId = item.user_id;
    } else {
      params.id = item.id;
    }
    this.ngZone.run(() => this.navCtrl.navigateForward([Roots.page + '/' + Roots.messageChat, params])).then();
  }

  formatDate(someDateTimeStamp: Date) {
    const dt = new Date(someDateTimeStamp);
    const date = dt.getDate();
    const today = new Date();
    const yesterday = new Date(Date.now() - 86400000);
    if (date === today.getDate() &&
      dt.getMonth() === today.getMonth() &&
      dt.getFullYear() === today.getFullYear()) {
      return 'Today';
    } else if (date === yesterday.getDate() &&
      dt.getMonth() === yesterday.getMonth() &&
      dt.getFullYear() === yesterday.getFullYear()) {
      return 'Yesterday';
    } else {
      return this.days[dt.getDay()] + ', ' + this.days[dt.getMonth()] + ' ' + (date > 9 ? date : '0' + date);
    }
  }

  ngOnDestroy() {
    this.destroy$.next(true);
    this.destroy$.complete();
  }
}
