import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ButtonComponent, FlexComponent, CheckboxComponent } from 'ui-essentials';
import { NewsletterSignupConfig } from '../../interfaces/conversion.interfaces';

@Component({
  selector: 'ui-newsletter-signup',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    ButtonComponent,
    FlexComponent,
    CheckboxComponent
  ],
  template: `
    <div 
      class="newsletter-signup"
      [class.newsletter-signup--inline]="config.variant === 'inline'"
      [class.newsletter-signup--modal]="config.variant === 'modal'"
      [class.newsletter-signup--sidebar]="config.variant === 'sidebar'"
      [class.newsletter-signup--footer]="config.variant === 'footer'">
      
      <div class="newsletter-signup__content">
        <!-- Header -->
        <div class="newsletter-signup__header">
          <h3 class="newsletter-signup__title">{{ config.title }}</h3>
          <p *ngIf="config.description" class="newsletter-signup__description">
            {{ config.description }}
          </p>
        </div>

        <!-- Success Message -->
        <div *ngIf="showSuccess" class="newsletter-signup__success">
          <div class="success-message">
            <span class="success-message__icon">✓</span>
            <span class="success-message__text">{{ config.successMessage }}</span>
          </div>
        </div>

        <!-- Form -->
        <form 
          *ngIf="!showSuccess"
          [formGroup]="signupForm" 
          (ngSubmit)="onSubmit()"
          class="newsletter-signup__form">
          
          <!-- Email Input -->
          <div class="form-group">
            <div class="email-input">
              <input
                type="email"
                formControlName="email"
                [placeholder]="config.placeholder"
                class="email-input__field"
                [class.email-input__field--error]="emailControl?.invalid && emailControl?.touched"
                [attr.aria-label]="config.placeholder">
              
              <ui-button
                type="submit"
                variant="filled"
                [size]="'medium'"
                [disabled]="signupForm.invalid || isLoading"
                [loading]="isLoading"
                class="email-input__button">
                {{ config.ctaText }}
              </ui-button>
            </div>
            
            <!-- Email Validation Error -->
            <div 
              *ngIf="emailControl?.invalid && emailControl?.touched" 
              class="form-group__error">
              <span *ngIf="emailControl?.errors?.['required']">Email is required</span>
              <span *ngIf="emailControl?.errors?.['email']">Please enter a valid email address</span>
            </div>
          </div>

          <!-- Privacy Checkbox -->
          <div *ngIf="config.showPrivacyCheckbox" class="form-group">
            <ui-checkbox
              formControlName="privacy"
              [required]="true"
              class="privacy-checkbox">
              <span class="privacy-checkbox__text">
                I agree to receive marketing communications and accept the 
                <a href="/privacy" target="_blank" class="privacy-checkbox__link">privacy policy</a>
              </span>
            </ui-checkbox>
            
            <div 
              *ngIf="privacyControl?.invalid && privacyControl?.touched" 
              class="form-group__error">
              <span>You must accept the privacy policy to continue</span>
            </div>
          </div>

          <!-- Privacy Text -->
          <p *ngIf="config.privacyText && !config.showPrivacyCheckbox" class="newsletter-signup__privacy">
            {{ config.privacyText }}
          </p>
        </form>
      </div>
    </div>
  `,
  styleUrls: ['./newsletter-signup.component.scss']
})
export class NewsletterSignupComponent {
  @Input() config!: NewsletterSignupConfig;
  @Output() signup = new EventEmitter<{ email: string; privacyAccepted?: boolean }>();

  signupForm: FormGroup;
  isLoading = false;
  showSuccess = false;

  constructor(private fb: FormBuilder) {
    this.signupForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      privacy: [false]
    });
  }

  ngOnInit() {
    if (this.config.showPrivacyCheckbox) {
      this.signupForm.get('privacy')?.setValidators([Validators.requiredTrue]);
    }
  }

  get emailControl() {
    return this.signupForm.get('email');
  }

  get privacyControl() {
    return this.signupForm.get('privacy');
  }

  async onSubmit() {
    if (this.signupForm.valid) {
      this.isLoading = true;
      
      try {
        const formValue = this.signupForm.value;
        this.signup.emit({
          email: formValue.email,
          privacyAccepted: formValue.privacy
        });

        // Simulate API call
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        this.showSuccess = true;
        this.signupForm.reset();
      } catch (error) {
        console.error('Newsletter signup failed:', error);
      } finally {
        this.isLoading = false;
      }
    } else {
      // Mark all fields as touched to show validation errors
      this.signupForm.markAllAsTouched();
    }
  }
}