import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ConnectionModalData } from '../../interfaces/generic-modal.interface';

@Component({
  selector: 'app-generic-connection-modal',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule
  ],
  template: `
    <div class="modal-overlay" (click)="onOverlayClick($event)">
      <div class="modal-container" (click)="$event.stopPropagation()">
        <!-- Header -->
        <div class="modal-header">
          <div class="header-icon">
            <div class="power-icon">
              <i class="material-icons">bolt</i>
            </div>
          </div>
          <h2 class="modal-title">{{ data.title }}</h2>
          <p class="modal-subtitle">{{ data.subtitle }}</p>
          <button class="close-button" (click)="closeModal()">
            <i class="material-icons">close</i>
          </button>
        </div>

        <!-- Content -->
        <form [formGroup]="connectionForm" (ngSubmit)="onSubmit()">
          <div class="modal-content">
            <!-- Campo Chave da API -->
            <div class="form-group">
              <label for="apiKey" class="field-label">Chave da API</label>
              <div class="custom-input">
                <input
                  id="apiKey"
                  type="text"
                  formControlName="apiKey"
                  placeholder="Cole sua chave de API aqui"
                  [class.error]="connectionForm.get('apiKey')?.invalid && connectionForm.get('apiKey')?.touched"
                />
              </div>
              <div class="error-message" *ngIf="connectionForm.get('apiKey')?.invalid && connectionForm.get('apiKey')?.touched">
                <span *ngIf="connectionForm.get('apiKey')?.errors?.['required']">
                  Chave da API é obrigatório
                </span>
              </div>
            </div>

            <!-- Campo Endpoint -->
            <div class="form-group">
              <label for="endpoint" class="field-label">Endpoint (opcional)</label>
              <div class="custom-input">
                <input
                  id="endpoint"
                  type="text"
                  formControlName="endpoint"
                  placeholder="https://api.exemplo.com"
                  [class.error]="connectionForm.get('endpoint')?.invalid && connectionForm.get('endpoint')?.touched"
                />
              </div>
              <div class="error-message" *ngIf="connectionForm.get('endpoint')?.invalid && connectionForm.get('endpoint')?.touched">
                <span *ngIf="connectionForm.get('endpoint')?.errors?.['url']">
                  Digite uma URL válida
                </span>
              </div>
            </div>
          </div>

          <!-- Actions -->
          <div class="modal-actions">
            <button 
              type="button"
              class="btn-cancel"
              (click)="closeModal()">
              Cancelar
            </button>
            
            <button 
              type="submit"
              class="btn-submit"
              [disabled]="connectionForm.invalid || isLoading">
              <i class="material-icons" *ngIf="!isLoading">refresh</i>
              <i class="material-icons loading" *ngIf="isLoading">sync</i>
              Conectar
            </button>
          </div>
        </form>
      </div>
    </div>
  `,
  styleUrl: './generic-connection-modal.component.scss'
})
export class GenericConnectionModalComponent {
  connectionForm: FormGroup;
  isLoading = false;

  constructor(
    private fb: FormBuilder,
    public dialogRef: MatDialogRef<GenericConnectionModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: ConnectionModalData
  ) {
    this.connectionForm = this.createForm();
  }

  private createForm(): FormGroup {
    const formConfig: any = {};
    
    this.data.fields.forEach(field => {
      const validators = [];
      
      if (field.required) {
        validators.push(Validators.required);
      }
      
      if (field.type === 'url') {
        validators.push(this.urlValidator);
      }

      formConfig[field.key] = [field.value || '', validators];
    });

    return this.fb.group(formConfig);
  }

  private urlValidator(control: any) {
    if (!control.value) return null;
    
    try {
      new URL(control.value);
      return null;
    } catch {
      return { url: true };
    }
  }

  closeModal(): void {
    this.dialogRef.close();
  }

  onOverlayClick(event: Event): void {
    // Fecha o modal se clicar no overlay (não no conteúdo)
    this.closeModal();
  }

  onSubmit(): void {
    if (this.connectionForm.valid) {
      this.isLoading = true;
      
      const formData = this.connectionForm.value;
      
      // Simular delay de rede
      setTimeout(() => {
        this.dialogRef.close({ 
          action: 'connect',
          data: formData 
        });
      }, 1000);
    }
  }
} 