import { ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { takeUntil } from 'rxjs';
import { CarouselModule, OwlOptions } from 'ngx-owl-carousel-o';
import { Unsub } from '../../../shared/class/unsub.class';
import { GuestService } from '../../../shared/services/guest.service';
import { LoaderService } from '../../../shared/services/loader.service';
import { TranslatePipe } from '@ngx-translate/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipes } from '../../../shared/pipes/translate/translate.pipe';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  standalone : true,
  imports : [CommonModule, TranslatePipes, RouterLink, CarouselModule, NgbAlertModule],
  providers : [TranslatePipe]
})
export class HomeComponent extends Unsub implements OnInit {
  @ViewChild('seachBackdrop') seachBackdrop!: ElementRef;
  @ViewChild('alert') alertElements!: ElementRef;
  data;
  setting;
  today = new Date();
  dropdownData;
  hideAlertsUntil: { [key: string]: number } = {};
  constructor(private guestService: GuestService, loaderService: LoaderService, private cookieService: CookieService, private sanitizer: DomSanitizer,private cdr: ChangeDetectorRef) {
     /**
     * This code calls the constructor of the parent class in a subclass. 
     * The super() function is used to initialize the parent class and allows access to its properties and methods. 
     * By calling  super(), the subclass can inherit and use the functionality of the parent class.
     **/
super(loaderService);
this.loaderService.showLoader();
    this.guestService
      .home()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.data = res;
          this.setting = res.setting;
          res.announcement?.forEach(alert => {
            const hideAlertsUntil = this.cookieService.get('anct' + alert.id);
            if (hideAlertsUntil) {
              this.hideAlertsUntil['anct' + alert.id] = parseInt(hideAlertsUntil, 10);
            }
          })
          res.announcements?.forEach(alert => {
            const hideAlertsUntil = this.cookieService.get('anct' + alert.id);
            if (hideAlertsUntil) {
              this.hideAlertsUntil['anct' + alert.id] = parseInt(hideAlertsUntil, 10);
            }
          })
          res.holidays?.forEach(alert => {
            const hideAlertsUntil = this.cookieService.get('holiday' + alert.id);
            if (hideAlertsUntil) {
              this.hideAlertsUntil['holiday' + alert.id] = parseInt(hideAlertsUntil, 10);
            }
          })
          this.loaderService.hideLoader();
        },
        error : ()=> this.loaderService.hideLoader()
      });
  }

  ngOnInit(): void {}

  search(event) {
    const data = {
        data: event.target.value,
    };
    this.guestService
      .searchArt(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.dropdownData = res;
          // Manually trigger change detection if needed
          this.cdr.detectChanges();
          if(this.dropdownData){
            const backdrop = this.seachBackdrop.nativeElement;
            backdrop.style.display = 'block'; // Hide the backdrop 
          }
        },
      });
  }
  closeSearchBakcDrop(){
    const backdrop = this.seachBackdrop.nativeElement;
    backdrop.style.display = 'none'; // Hide the backdrop 
    this.dropdownData = undefined;
  }

	customOptions: OwlOptions = {
    loop: true,
    mouseDrag: true,
    touchDrag: true,
    pullDrag: true,
    dots: true,
    navSpeed: 700,
    navText: ['<i class="fe fe-arrow-left"></i>', '<i class="fe fe-arrow-right"></i>'],
    responsive: {
      0: {
        items: 1
      },
      400: {
        items: 1
      },
      740: {
        items: 1
      },
      940: {
        items: 1
      }
    },
    nav: true
  };

  
  heightOfAlert(value){
    // this.heightOfAlerts = value; 
  }

  heightOfAlerts = 0
  
  elementsHeight = 0;
  ngAfterViewChecked() {
    let height = this.alertElements.nativeElement.offsetHeight;
    if (this.elementsHeight != height) {
      this.heightOfAlerts = height;
      this.elementsHeight = height;
      let ele: HTMLElement | null = document.querySelector('.horizontal-main.landing-header');
      if(ele){
        ele.style.top = height + 'px' ;
        ele.classList.add("position-fixed");        
      }
    }
  }

  // hideAlertsUntil: { [key: string]: number } = {};

  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
  
  // Function to add alpha channel to RGB color
  addAlphaChannel(color: string, alpha: number): string {
    if (this.isRGBColor(color)) {
      // Extracting the RGB values
      const rgbValues = color.match(/\d+/g);
      // Constructing the RGBA color value
      const rgbaColor = `rgba(${rgbValues?.[0]}, ${rgbValues?.[1]}, ${rgbValues?.[2]}, ${alpha})`;
      return rgbaColor;
    } else if (this.isHexColor(color)) {
        // Convert hex to RGB
        const rgbValues = this.hexToRgb(color);
        // Constructing the RGBA color value
        const rgbaColor = `rgba(${rgbValues.r}, ${rgbValues.g}, ${rgbValues.b}, ${alpha})`;
        return rgbaColor;
    } else {
        // Not a valid RGB or hex color, return original color
        return color;
    }
  }
  
  isRGBColor(color: string): boolean {
    return /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*\d+(\.\d+)?\s*)?\)$/i.test(color);
  }

  isHexColor(color: string): boolean {
    return /^#[0-9A-F]{6}$/i.test(color);
  }

  hexToRgb(hex: string): { r: number, g: number, b: number } {
    // Removing '#' if present
    hex = hex.replace('#', '');
    
    // Splitting into R, G, B values
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    
    return { r, g, b };
  }
  dismissAlert(alert, type) {
    const hideAlertsUntil = (Date.now() + (30 * 60 * 1000)).toString();
    this.cookieService.set(type + alert.id, hideAlertsUntil, undefined, '/'); // Set cookie for 30 minutes from now
    this.hideAlertsUntil[type + alert.id] = parseInt(hideAlertsUntil, 10);
  }

  isAlertVisible(alert, type) {
    return !alert.dismissed && (!this.hideAlertsUntil?.[type + alert.id] || this.hideAlertsUntil?.[type + alert.id] < Date.now());
  }

  override ngOnDestroy() {
    
    let ele: HTMLElement | null = document.querySelector('.horizontal-main.landing-header');
    if(ele){
      ele.style.top = '0px' ;
      ele.classList.remove("position-fixed");      
    }
  }
}
