import { CommonModule } from '@angular/common';
import { Component, inject, Input, output, SimpleChanges } from '@angular/core';
import { RouterModule } from '@angular/router';

import { NgbModule, NgbRatingConfig } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { Observable } from 'rxjs';

import { environment } from '../../../../../environments/environment';
import { AddToCompareAction } from '../../../../shared/action/compare.action';
import {
  AddToWishlistAction,
  DeleteWishlistAction,
} from '../../../../shared/action/wishlist.action';
import * as data from '../../../../shared/data/owl-carousel';
import { IProduct } from '../../../../shared/interface/product.interface';
import { IDeal, IDealOfDays } from '../../../../shared/interface/theme.interface';
import { CurrencySymbolPipe } from '../../../../shared/pipe/currency-symbol.pipe';
import { ProductState } from '../../../../shared/state/product.state';

@Component({
  selector: 'app-deal',
  imports: [
    CommonModule,
    CarouselModule,
    RouterModule,
    NgbModule,
    TranslateModule,
    CurrencySymbolPipe,
  ],
  templateUrl: './deal.html',
  styleUrl: './deal.scss',
})
export class Deal {
  public config = inject(NgbRatingConfig);
  private store = inject(Store);

  @Input() data?: IDealOfDays;
  public storageURL = environment.storageURL;

  product$: Observable<IProduct[]> = inject(Store).select(ProductState.productByIds);

  readonly isDeal = output<boolean>();

  public dealSlider = data.singleSlider;
  public deals: IDeal[] = [];

  constructor() {
    this.config.max = 5;
    this.config.readonly = true;
  }

  ngOnChanges(changes: SimpleChanges) {
    let dealsArray = changes['data']?.currentValue?.deals;
    this.product$.subscribe(products => {
      dealsArray.map((deal: any) => {
        deal.product = products.find(product => product.id === deal.product_id);
      });
      this.deals = dealsArray;
      this.isDeal.emit(this.deals?.length ? true : false);
      this.startTimers();
    });
  }

  startTimers() {
    for (let counterItem of this.deals) {
      const endDate = new Date(counterItem.end_date).getTime();
      const currentTime = new Date().getTime();
      const timeDifference = endDate - currentTime;

      if (timeDifference > 0) {
        counterItem.remainingTime = this.calculateRemainingTime(timeDifference);
        setInterval(() => {
          counterItem.remainingTime = this.calculateRemainingTime(endDate - new Date().getTime());
        }, 1000);
      }
    }
  }

  calculateRemainingTime(timeDifference: number) {
    const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
    return { days, hours, minutes, seconds };
  }

  addToWishlist(product: IProduct) {
    product['is_wishlist'] = !product['is_wishlist'];
    let action = product['is_wishlist']
      ? new AddToWishlistAction({ product_id: product.id })
      : new DeleteWishlistAction(product.id);
    if (action) {
      this.store.dispatch(action);
    }
  }

  addToCompare(id: number) {
    this.store.dispatch(new AddToCompareAction({ product_id: id }));
  }
}
