import { Component, Input, ChangeDetectionStrategy, ViewEncapsulation, signal, computed, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ContainerComponent } from 'ui-essentials';
import { SearchBarComponent } from 'ui-essentials';
import { FAQConfig, FAQItem } from '../../interfaces/content.interfaces';

@Component({
  selector: 'ui-lp-faq',
  standalone: true,
  imports: [CommonModule, FormsModule, ContainerComponent, SearchBarComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <section class="ui-lp-faq" [class]="getComponentClasses()">
      <ui-container [size]="'lg'" [padding]="'md'">
        @if (config().title || config().subtitle) {
          <div class="ui-lp-faq__header">
            @if (config().title) {
              <h2 class="ui-lp-faq__title">{{ config().title }}</h2>
            }
            
            @if (config().subtitle) {
              <p class="ui-lp-faq__subtitle">{{ config().subtitle }}</p>
            }
          </div>
        }
        
        @if (config().searchEnabled) {
          <div class="ui-lp-faq__search">
            <ui-search-bar
              [placeholder]="'Search FAQ...'"
              [(ngModel)]="searchQuery"
              [size]="'lg'"
              [clearable]="true">
            </ui-search-bar>
          </div>
        }
        
        @if (filteredItems().length > 0) {
          <div class="ui-lp-faq__items">
            @for (item of filteredItems(); track item.id) {
              <div 
                class="ui-lp-faq__item"
                [class.ui-lp-faq__item--open]="item.isOpen">
                <button 
                  class="ui-lp-faq__question"
                  (click)="toggleItem(item)"
                  [attr.aria-expanded]="item.isOpen"
                  [attr.aria-controls]="'faq-answer-' + item.id">
                  <span class="ui-lp-faq__question-text">{{ item.question }}</span>
                  <span class="ui-lp-faq__toggle-icon" aria-hidden="true">
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                      <path d="M8 4l4 4H4l4-4z"/>
                    </svg>
                  </span>
                </button>
                
                <div 
                  class="ui-lp-faq__answer"
                  [id]="'faq-answer-' + item.id"
                  [attr.aria-labelledby]="'faq-question-' + item.id">
                  <div class="ui-lp-faq__answer-content">
                    <p>{{ item.answer }}</p>
                  </div>
                </div>
              </div>
            }
          </div>
        } @else {
          <div class="ui-lp-faq__empty">
            <p>No FAQs found matching your search.</p>
          </div>
        }
      </ui-container>
    </section>
  `,
  styleUrl: './faq-section.component.scss'
})
export class FAQSectionComponent {
  config = signal<FAQConfig>({
    title: 'Frequently Asked Questions',
    items: [],
    searchEnabled: true,
    expandMultiple: false,
    theme: 'default'
  });

  searchQuery = signal<string>('');

  @Input() set configuration(value: FAQConfig) {
    // Initialize isOpen state for items if not provided
    const itemsWithState = value.items.map(item => ({
      ...item,
      isOpen: item.isOpen ?? false
    }));
    
    this.config.set({
      ...value,
      items: itemsWithState
    });
  }

  filteredItems = computed(() => {
    const query = this.searchQuery().toLowerCase().trim();
    if (!query) return this.config().items;

    return this.config().items.filter(item =>
      item.question.toLowerCase().includes(query) ||
      item.answer.toLowerCase().includes(query)
    );
  });

  getComponentClasses(): string {
    const classes = ['ui-lp-faq'];
    
    if (this.config().theme) {
      classes.push(`ui-lp-faq--${this.config().theme}`);
    }
    
    return classes.join(' ');
  }

  toggleItem(item: FAQItem): void {
    const currentConfig = this.config();
    const items = [...currentConfig.items];
    
    if (!currentConfig.expandMultiple) {
      // Close all other items if expandMultiple is false
      items.forEach(i => {
        if (i.id !== item.id) {
          i.isOpen = false;
        }
      });
    }
    
    // Toggle the clicked item
    const targetItem = items.find(i => i.id === item.id);
    if (targetItem) {
      targetItem.isOpen = !targetItem.isOpen;
    }
    
    this.config.set({
      ...currentConfig,
      items
    });
  }
}