import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ViewEncapsulation, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule, FormControl, Validators } from '@angular/forms';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { ButtonComponent } from 'ui-essentials';
import { ContainerComponent } from 'ui-essentials';
import { FlexComponent } from 'ui-essentials';
import { GridContainerComponent } from 'ui-essentials';
import { DividerComponent } from 'ui-essentials';
import { FooterConfig, FooterLink } from '../../interfaces/navigation.interfaces';

@Component({
  selector: 'ui-lp-footer',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    FontAwesomeModule,
    ButtonComponent,
    ContainerComponent,
    FlexComponent,
    GridContainerComponent,
    DividerComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <footer 
      class="ui-lp-footer"
      [class.ui-lp-footer--theme-dark]="config().theme === 'dark'"
      [attr.aria-label]="'Site footer'">
      
      <!-- Main Footer Content -->
      <div class="ui-lp-footer__main">
        <ui-container [size]="'xl'" [padding]="'md'">
          <ui-grid-container 
            [style.grid-template-columns]="getGridColumns()"
            [gap]="'lg'"
            class="ui-lp-footer__grid">
            
            <!-- Company/Brand Section -->
            @if (config().logo || config().newsletter) {
              <div class="ui-lp-footer__brand-section">
                @if (config().logo) {
                  <div class="ui-lp-footer__logo">
                    @if (config().logo!.imageUrl) {
                      <a 
                        [routerLink]="config().logo?.url || '/'"
                        class="ui-lp-footer__logo-link">
                        <img 
                          [src]="config().logo?.imageUrl"
                          [alt]="config().logo?.text || 'Logo'"
                          [width]="config().logo?.width || 120"
                          [height]="config().logo?.height || 40"
                          class="ui-lp-footer__logo-image">
                      </a>
                    } @else if (config().logo!.text) {
                      <a 
                        [routerLink]="config().logo?.url || '/'"
                        class="ui-lp-footer__logo-text">
                        {{ config().logo?.text }}
                      </a>
                    }
                  </div>
                }
                
                @if (config().newsletter) {
                  <div class="ui-lp-footer__newsletter">
                    <h3 class="ui-lp-footer__newsletter-title">
                      {{ config().newsletter!.title }}
                    </h3>
                    
                    @if (config().newsletter!.description) {
                      <p class="ui-lp-footer__newsletter-description">
                        {{ config().newsletter!.description }}
                      </p>
                    }
                    
                    <form class="ui-lp-footer__newsletter-form" (ngSubmit)="handleNewsletterSubmit()">
                      <div class="ui-lp-footer__newsletter-input-group">
                        <input
                          type="email"
                          [formControl]="emailControl"
                          [placeholder]="config().newsletter!.placeholder"
                          class="ui-lp-footer__newsletter-input"
                          [attr.aria-label]="'Email address'">
                        <ui-button
                          type="submit"
                          [variant]="'filled'"
                          [size]="'medium'"
                          [disabled]="emailControl.invalid"
                          class="ui-lp-footer__newsletter-button">
                          {{ config().newsletter!.buttonText }}
                        </ui-button>
                      </div>
                      
                      @if (newsletterStatus()) {
                        <div 
                          class="ui-lp-footer__newsletter-status"
                          [class.ui-lp-footer__newsletter-status--success]="newsletterStatus() === 'success'"
                          [class.ui-lp-footer__newsletter-status--error]="newsletterStatus() === 'error'">
                          @switch (newsletterStatus()) {
                            @case ('success') {
                              Thank you for subscribing!
                            }
                            @case ('error') {
                              There was an error. Please try again.
                            }
                          }
                        </div>
                      }
                    </form>
                  </div>
                }
                
                @if (config().socialLinks && config().socialLinks!.length > 0) {
                  <div class="ui-lp-footer__social">
                    <h4 class="ui-lp-footer__social-title">Follow Us</h4>
                    <div class="ui-lp-footer__social-links">
                      @for (social of config().socialLinks || []; track social.id) {
                        <a
                          [href]="social.url"
                          target="_blank"
                          rel="noopener noreferrer"
                          class="ui-lp-footer__social-link"
                          [attr.aria-label]="social.label || social.platform">
                          @if (social.icon) {
                            <i [class]="social.icon" class="ui-lp-footer__social-icon" aria-hidden="true"></i>
                          } @else {
                            <i [class]="getSocialIcon(social.platform)" class="ui-lp-footer__social-icon" aria-hidden="true"></i>
                          }
                        </a>
                      }
                    </div>
                  </div>
                }
              </div>
            }
            
            <!-- Footer Columns -->
            @for (column of config().columns; track column.id) {
              <div class="ui-lp-footer__column">
                <h4 class="ui-lp-footer__column-title">{{ column.title }}</h4>
                <ul class="ui-lp-footer__column-list">
                  @for (item of column.items; track item.id) {
                    <li class="ui-lp-footer__column-item">
                      <a
                        [href]="item.url"
                        [routerLink]="item.route"
                        [target]="item.target || '_self'"
                        class="ui-lp-footer__column-link"
                        (click)="handleLinkClick(item)">
                        @if (item.icon) {
                          <span class="ui-lp-footer__link-icon">{{ item.icon }}</span>
                        }
                        {{ item.label }}
                      </a>
                    </li>
                  }
                </ul>
              </div>
            }
          </ui-grid-container>
        </ui-container>
      </div>
      
      <!-- Footer Bottom -->
      @if (config().showDivider !== false) {
        <ui-divider></ui-divider>
      }
      
      <div class="ui-lp-footer__bottom">
        <ui-container [size]="'xl'" [padding]="'md'">
          <ui-flex 
            [justify]="'between'" 
            [align]="'center'"
            [wrap]="'wrap'"
            [gap]="'md'"
            class="ui-lp-footer__bottom-content">
            
            <!-- Copyright -->
            @if (config().copyright) {
              <div class="ui-lp-footer__copyright">
                {{ config().copyright }}
              </div>
            }
            
            <!-- Legal Links -->
            @if (config().legalLinks && config().legalLinks!.length > 0) {
              <ul class="ui-lp-footer__legal-links">
                @for (link of config().legalLinks || []; track link.id; let last = $last) {
                  <li class="ui-lp-footer__legal-item">
                    <a
                      [href]="link.url"
                      [routerLink]="link.route"
                      [target]="link.target || '_self'"
                      class="ui-lp-footer__legal-link"
                      (click)="handleLinkClick(link)">
                      {{ link.label }}
                    </a>
                    @if (!last) {
                      <span class="ui-lp-footer__legal-separator" aria-hidden="true">•</span>
                    }
                  </li>
                }
              </ul>
            }
          </ui-flex>
        </ui-container>
      </div>
    </footer>
  `,
  styleUrl: './footer-section.component.scss'
})
export class FooterSectionComponent {
  config = signal<FooterConfig>({
    columns: [],
    theme: 'light',
    showDivider: true
  });
  
  emailControl = new FormControl('', [Validators.required, Validators.email]);
  newsletterStatus = signal<'success' | 'error' | null>(null);
  
  @Input() set configuration(value: FooterConfig) {
    this.config.set(value);
  }
  
  @Output() linkClicked = new EventEmitter<FooterLink>();
  @Output() newsletterSubmitted = new EventEmitter<string>();
  
  getGridColumns(): string {
    let columns = this.config().columns.length;
    
    // Add brand section if logo or newsletter exists
    if (this.config().logo || this.config().newsletter) {
      columns += 1;
    }
    
    const gridColumns = Math.min(columns, 5);
    return `repeat(${gridColumns}, 1fr)`;
  }
  
  handleLinkClick(link: FooterLink): void {
    if (link.action) {
      link.action();
    }
    this.linkClicked.emit(link);
  }
  
  handleNewsletterSubmit(): void {
    if (this.emailControl.valid && this.emailControl.value) {
      const email = this.emailControl.value;
      
      const newsletter = this.config().newsletter;
      if (newsletter && newsletter.onSubmit) {
        try {
          newsletter.onSubmit(email);
          this.newsletterStatus.set('success');
          this.emailControl.reset();
          this.newsletterSubmitted.emit(email);
        } catch (error) {
          console.error('Newsletter submission error:', error);
          this.newsletterStatus.set('error');
        }
      }
      
      // Reset status after 5 seconds
      setTimeout(() => {
        this.newsletterStatus.set(null);
      }, 5000);
    }
  }
  
  getSocialIcon(platform: string): string {
    const icons: Record<string, string> = {
      facebook: 'fab fa-facebook',
      twitter: 'fab fa-twitter',
      instagram: 'fab fa-instagram',
      linkedin: 'fab fa-linkedin',
      youtube: 'fab fa-youtube',
      github: 'fab fa-github',
      dribbble: 'fab fa-dribbble'
    };
    
    return icons[platform] || 'fas fa-link';
  }
}