import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, AbstractControl } from '@angular/forms';
import { ButtonComponent, FlexComponent, ContainerComponent } from 'ui-essentials';
import { ContactFormConfig, FormField } from '../../interfaces/conversion.interfaces';

@Component({
  selector: 'ui-contact-form',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    ButtonComponent,
    FlexComponent,
    ContainerComponent
  ],
  template: `
    <div class="contact-form">
      <ui-container>
        
        <!-- Header -->
        <div *ngIf="config.title || config.description" class="contact-form__header">
          <h2 *ngIf="config.title" class="contact-form__title">{{ config.title }}</h2>
          <p *ngIf="config.description" class="contact-form__description">{{ config.description }}</p>
        </div>

        <!-- Success Message -->
        <div *ngIf="showSuccess" class="contact-form__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]="contactForm" 
          (ngSubmit)="onSubmit()"
          class="contact-form__form"
          [class.contact-form__form--single-column]="config.layout === 'single-column'"
          [class.contact-form__form--two-column]="config.layout === 'two-column'"
          [class.contact-form__form--inline]="config.layout === 'inline'">
          
          <!-- Dynamic Fields -->
          <div 
            *ngFor="let field of config.fields; trackBy: trackByField"
            class="form-field"
            [class.form-field--full-width]="field.type === 'textarea' || config.layout === 'single-column'"
            [class.form-field--checkbox]="field.type === 'checkbox'">
            
            <!-- Text Input -->
            <div *ngIf="field.type === 'text' || field.type === 'email' || field.type === 'tel'" class="input-group">
              <label [for]="field.name" class="input-group__label">
                {{ field.label }}
                <span *ngIf="field.required" class="input-group__required">*</span>
              </label>
              <input
                [id]="field.name"
                [type]="field.type"
                [formControlName]="field.name"
                [placeholder]="field.placeholder || ''"
                class="input-group__input"
                [class.input-group__input--error]="isFieldInvalid(field.name)"
                [attr.aria-describedby]="field.name + '-error'"
                [attr.aria-invalid]="isFieldInvalid(field.name)">
              
              <div 
                *ngIf="isFieldInvalid(field.name)" 
                [id]="field.name + '-error'"
                class="input-group__error"
                role="alert">
                {{ getFieldError(field.name) }}
              </div>
            </div>

            <!-- Textarea -->
            <div *ngIf="field.type === 'textarea'" class="input-group">
              <label [for]="field.name" class="input-group__label">
                {{ field.label }}
                <span *ngIf="field.required" class="input-group__required">*</span>
              </label>
              <textarea
                [id]="field.name"
                [formControlName]="field.name"
                [placeholder]="field.placeholder || ''"
                [rows]="field.rows || 4"
                class="input-group__textarea"
                [class.input-group__textarea--error]="isFieldInvalid(field.name)"
                [attr.aria-describedby]="field.name + '-error'"
                [attr.aria-invalid]="isFieldInvalid(field.name)">
              </textarea>
              
              <div 
                *ngIf="isFieldInvalid(field.name)" 
                [id]="field.name + '-error'"
                class="input-group__error"
                role="alert">
                {{ getFieldError(field.name) }}
              </div>
            </div>

            <!-- Select -->
            <div *ngIf="field.type === 'select'" class="input-group">
              <label [for]="field.name" class="input-group__label">
                {{ field.label }}
                <span *ngIf="field.required" class="input-group__required">*</span>
              </label>
              <select
                [id]="field.name"
                [formControlName]="field.name"
                class="input-group__select"
                [class.input-group__select--error]="isFieldInvalid(field.name)"
                [attr.aria-describedby]="field.name + '-error'"
                [attr.aria-invalid]="isFieldInvalid(field.name)">
                <option value="" disabled>{{ field.placeholder || 'Select an option...' }}</option>
                <option *ngFor="let option of field.options" [value]="option.value">
                  {{ option.label }}
                </option>
              </select>
              
              <div 
                *ngIf="isFieldInvalid(field.name)" 
                [id]="field.name + '-error'"
                class="input-group__error"
                role="alert">
                {{ getFieldError(field.name) }}
              </div>
            </div>

            <!-- Checkbox -->
            <div *ngIf="field.type === 'checkbox'" class="checkbox-group">
              <label class="checkbox-group__label">
                <input
                  type="checkbox"
                  [formControlName]="field.name"
                  class="checkbox-group__input"
                  [attr.aria-describedby]="field.name + '-error'"
                  [attr.aria-invalid]="isFieldInvalid(field.name)">
                <span class="checkbox-group__checkmark"></span>
                <span class="checkbox-group__text">
                  {{ field.label }}
                  <span *ngIf="field.required" class="checkbox-group__required">*</span>
                </span>
              </label>
              
              <div 
                *ngIf="isFieldInvalid(field.name)" 
                [id]="field.name + '-error'"
                class="checkbox-group__error"
                role="alert">
                {{ getFieldError(field.name) }}
              </div>
            </div>
          </div>

          <!-- Submit Button -->
          <div class="contact-form__submit">
            <ui-button
              type="submit"
              variant="filled"
              [size]="'large'"
              [disabled]="contactForm.invalid || isLoading"
              [loading]="isLoading"
              class="contact-form__button">
              {{ config.submitText }}
            </ui-button>
          </div>
        </form>
      </ui-container>
    </div>
  `,
  styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent implements OnInit {
  @Input() config!: ContactFormConfig;
  @Output() submit = new EventEmitter<any>();

  contactForm: FormGroup = new FormGroup({});
  isLoading = false;
  showSuccess = false;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.buildForm();
  }

  private buildForm() {
    const formControls: { [key: string]: any } = {};

    this.config.fields.forEach(field => {
      const validators = [];
      
      if (field.required) {
        if (field.type === 'checkbox') {
          validators.push(Validators.requiredTrue);
        } else {
          validators.push(Validators.required);
        }
      }

      if (field.type === 'email') {
        validators.push(Validators.email);
      }

      if (field.validation) {
        if (field.validation.minLength) {
          validators.push(Validators.minLength(field.validation.minLength));
        }
        if (field.validation.maxLength) {
          validators.push(Validators.maxLength(field.validation.maxLength));
        }
        if (field.validation.pattern) {
          validators.push(Validators.pattern(field.validation.pattern));
        }
        if (field.validation.custom) {
          validators.push((control: AbstractControl) => {
            const error = field.validation!.custom!(control.value);
            return error ? { custom: error } : null;
          });
        }
      }

      const defaultValue = field.type === 'checkbox' ? false : '';
      formControls[field.name] = [defaultValue, validators];
    });

    this.contactForm = this.fb.group(formControls);
  }

  trackByField(index: number, field: FormField): string {
    return field.name;
  }

  isFieldInvalid(fieldName: string): boolean {
    const control = this.contactForm.get(fieldName);
    return !!(control && control.invalid && control.touched);
  }

  getFieldError(fieldName: string): string {
    const control = this.contactForm.get(fieldName);
    if (!control || !control.errors) return '';

    const field = this.config.fields.find(f => f.name === fieldName);
    
    if (control.errors['required']) {
      return `${field?.label} is required`;
    }
    if (control.errors['email']) {
      return 'Please enter a valid email address';
    }
    if (control.errors['minlength']) {
      return `${field?.label} must be at least ${control.errors['minlength'].requiredLength} characters`;
    }
    if (control.errors['maxlength']) {
      return `${field?.label} must not exceed ${control.errors['maxlength'].requiredLength} characters`;
    }
    if (control.errors['pattern']) {
      return `${field?.label} format is invalid`;
    }
    if (control.errors['custom']) {
      return control.errors['custom'];
    }
    if (control.errors['requiredTrue']) {
      return `${field?.label} must be checked`;
    }

    return 'Invalid input';
  }

  async onSubmit() {
    if (this.contactForm.valid) {
      this.isLoading = true;
      
      try {
        this.submit.emit(this.contactForm.value);

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