import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ViewEncapsulation, signal, computed, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ContainerComponent } from 'ui-essentials';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { IconDefinition } from '@fortawesome/fontawesome-svg-core';
import { faQuoteLeft, faStar, faChevronLeft, faChevronRight, faCheck } from '@fortawesome/free-solid-svg-icons';
import { TestimonialCarouselConfig, TestimonialItem } from '../../interfaces/social-proof.interfaces';

@Component({
  selector: 'ui-lp-testimonial-carousel',
  standalone: true,
  imports: [CommonModule, ContainerComponent, FaIconComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <section 
      class="ui-lp-testimonial-carousel"
      [class]="getTestimonialCarouselClasses()"
      [attr.aria-label]="'Testimonials section'">
      
      <ui-container [size]="'xl'" [padding]="'lg'">
        @if (config().title || config().subtitle) {
          <div class="ui-lp-testimonial-carousel__header">
            @if (config().title) {
              <h2 class="ui-lp-testimonial-carousel__title">{{ config().title }}</h2>
            }
            @if (config().subtitle) {
              <p class="ui-lp-testimonial-carousel__subtitle">{{ config().subtitle }}</p>
            }
          </div>
        }
        
        <div class="ui-lp-testimonial-carousel__container">
          @if (config().showNavigation && config().testimonials.length > config().itemsPerView!) {
            <button 
              class="ui-lp-testimonial-carousel__nav ui-lp-testimonial-carousel__nav--prev"
              (click)="previousSlide()"
              [disabled]="currentSlide() === 0"
              [attr.aria-label]="'Previous testimonial'">
              <fa-icon [icon]="faChevronLeft"></fa-icon>
            </button>
          }
          
          <div class="ui-lp-testimonial-carousel__viewport">
            <div 
              class="ui-lp-testimonial-carousel__track"
              [style.transform]="'translateX(' + translateX() + '%)'">
              
              @for (testimonial of config().testimonials; track testimonial.id; let index = $index) {
                <div 
                  class="ui-lp-testimonial-carousel__slide"
                  [style.width]="slideWidth() + '%'">
                  
                  <div class="ui-lp-testimonial-carousel__item">
                    @if (config().variant === 'quote') {
                      <div class="ui-lp-testimonial-carousel__quote-icon">
                        <fa-icon [icon]="faQuoteLeft"></fa-icon>
                      </div>
                    }
                    
                    <div class="ui-lp-testimonial-carousel__content">
                      <p class="ui-lp-testimonial-carousel__text">{{ testimonial.content }}</p>
                      
                      @if (config().showRatings && testimonial.rating) {
                        <div class="ui-lp-testimonial-carousel__rating">
                          @for (star of getRatingArray(testimonial.rating); track $index) {
                            <fa-icon [icon]="faStar" class="ui-lp-testimonial-carousel__star"></fa-icon>
                          }
                        </div>
                      }
                    </div>
                    
                    <div class="ui-lp-testimonial-carousel__author">
                      @if (testimonial.avatar) {
                        <div class="ui-lp-testimonial-carousel__avatar">
                          <img 
                            [src]="testimonial.avatar" 
                            [alt]="testimonial.name"
                            loading="lazy">
                        </div>
                      }
                      
                      <div class="ui-lp-testimonial-carousel__author-info">
                        <div class="ui-lp-testimonial-carousel__author-name">
                          {{ testimonial.name }}
                          @if (testimonial.verified) {
                            <fa-icon [icon]="faCheck" class="ui-lp-testimonial-carousel__verified"></fa-icon>
                          }
                        </div>
                        @if (testimonial.title || testimonial.company) {
                          <div class="ui-lp-testimonial-carousel__author-title">
                            @if (testimonial.title) {
                              <span>{{ testimonial.title }}</span>
                            }
                            @if (testimonial.title && testimonial.company) {
                              <span> at </span>
                            }
                            @if (testimonial.company) {
                              <span>{{ testimonial.company }}</span>
                            }
                          </div>
                        }
                      </div>
                    </div>
                  </div>
                </div>
              }
            </div>
          </div>
          
          @if (config().showNavigation && config().testimonials.length > config().itemsPerView!) {
            <button 
              class="ui-lp-testimonial-carousel__nav ui-lp-testimonial-carousel__nav--next"
              (click)="nextSlide()"
              [disabled]="currentSlide() >= maxSlide()"
              [attr.aria-label]="'Next testimonial'">
              <fa-icon [icon]="faChevronRight"></fa-icon>
            </button>
          }
        </div>
        
        @if (config().showDots && config().testimonials.length > config().itemsPerView!) {
          <div class="ui-lp-testimonial-carousel__dots">
            @for (dot of dotsArray(); track $index; let index = $index) {
              <button 
                class="ui-lp-testimonial-carousel__dot"
                [class.ui-lp-testimonial-carousel__dot--active]="currentSlide() === index"
                (click)="goToSlide(index)"
                [attr.aria-label]="'Go to testimonial ' + (index + 1)">
              </button>
            }
          </div>
        }
      </ui-container>
    </section>
  `,
  styleUrl: './testimonial-carousel.component.scss'
})
export class TestimonialCarouselComponent implements OnInit, OnDestroy {
  config = signal<TestimonialCarouselConfig>({
    testimonials: [],
    autoPlay: false,
    autoPlayDelay: 5000,
    showDots: true,
    showNavigation: true,
    itemsPerView: 1,
    variant: 'card',
    showRatings: true
  });
  
  currentSlide = signal(0);
  private autoPlayInterval?: number;
  
  faQuoteLeft = faQuoteLeft;
  faStar = faStar;
  faChevronLeft = faChevronLeft;
  faChevronRight = faChevronRight;
  faCheck = faCheck;
  
  slideWidth = computed(() => 100 / this.config().itemsPerView!);
  translateX = computed(() => -this.currentSlide() * this.slideWidth());
  maxSlide = computed(() => Math.max(0, this.config().testimonials.length - this.config().itemsPerView!));
  dotsArray = computed(() => Array(this.maxSlide() + 1).fill(0));
  
  @Input() set configuration(value: TestimonialCarouselConfig) {
    this.config.set(value);
  }
  
  @Output() testimonialClicked = new EventEmitter<TestimonialItem>();
  
  getTestimonialCarouselClasses(): string {
    const classes = [
      'ui-lp-testimonial-carousel',
      `ui-lp-testimonial-carousel--${this.config().variant}`,
    ];
    
    return classes.join(' ');
  }
  
  ngOnInit(): void {
    if (this.config().autoPlay) {
      this.startAutoPlay();
    }
  }
  
  ngOnDestroy(): void {
    this.stopAutoPlay();
  }
  
  nextSlide(): void {
    const nextIndex = this.currentSlide() + 1;
    if (nextIndex <= this.maxSlide()) {
      this.currentSlide.set(nextIndex);
    } else if (this.config().autoPlay) {
      this.currentSlide.set(0);
    }
  }
  
  previousSlide(): void {
    const prevIndex = this.currentSlide() - 1;
    if (prevIndex >= 0) {
      this.currentSlide.set(prevIndex);
    }
  }
  
  goToSlide(index: number): void {
    this.currentSlide.set(index);
  }
  
  getRatingArray(rating: number): number[] {
    return Array(Math.floor(rating)).fill(0);
  }
  
  private startAutoPlay(): void {
    this.autoPlayInterval = window.setInterval(() => {
      this.nextSlide();
    }, this.config().autoPlayDelay);
  }
  
  private stopAutoPlay(): void {
    if (this.autoPlayInterval) {
      clearInterval(this.autoPlayInterval);
      this.autoPlayInterval = undefined;
    }
  }
}