import { CommonModule } from "@angular/common";
import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from "@angular/core";
import { CustomInputComponent } from "../inputs/custom-input/custom-input.component";
import { CepService } from "./cep.service";
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
import { Subscription, debounceTime, distinctUntilChanged } from "rxjs";

export interface AddressData {
  cep?: string;
  state?: string;
  city?: string;
  neighborhood?: string;
  street?: string;
  number?: string;
  complement?: string;
}

@Component({
  selector: "app-address-form",
  standalone: true,
  imports: [CommonModule, CustomInputComponent, ReactiveFormsModule],
  templateUrl: "./address-form.component.html",
  styleUrl: "./address-form.component.scss",
})
export class AddressFormComponent implements OnInit, OnDestroy {
  @Input() initialData: AddressData = {};
  @Input() title: string = "Endereço";
  @Input() isReadonly: boolean = false;
  @Input() showSaveButton: boolean = true;
  @Input() showCancelButton: boolean = true;
  
  @Output() dataChange = new EventEmitter<AddressData>();
  @Output() formValidChange = new EventEmitter<boolean>();
  @Output() save = new EventEmitter<AddressData>();
  @Output() cancel = new EventEmitter<void>();
  @Output() cepSearched = new EventEmitter<any>();

  form!: FormGroup;
  isLoading = false;
  isFormDirty = false;
  private subscriptions = new Subscription();

  fields = [
    {
      key: "cep",
      type: "text",
      label: "CEP",
      mask: "00000-000",
      required: false,
      placeholder: "00000-000"
    },
    {
      key: "state",
      type: "text",
      label: "Estado",
      required: false,
      readOnly: true,
      placeholder: "Estado (preenchido automaticamente)"
    },
    {
      key: "city",
      type: "text",
      label: "Cidade",
      required: false,
      readOnly: true,
      placeholder: "Cidade (preenchida automaticamente)"
    },
    {
      key: "neighborhood",
      type: "text",
      label: "Bairro",
      required: false,
      readOnly: true,
      placeholder: "Bairro (preenchido automaticamente)"
    },
    {
      key: "street",
      type: "text",
      label: "Rua",
      required: false,
      readOnly: true,
      placeholder: "Rua (preenchida automaticamente)"
    },
    {
      key: "number",
      type: "text",
      label: "Número",
      required: false,
      placeholder: "Número da residência"
    },
    {
      key: "complement",
      type: "text",
      label: "Complemento",
      required: false,
      placeholder: "Apto, bloco, etc. (opcional)"
    },
  ];

  constructor(private fb: FormBuilder, private cepService: CepService) {}

  ngOnInit() {
    this.initializeForm();
    this.setupFormListeners();
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }

  private initializeForm() {
    const formConfig: { [key: string]: any } = {};
    
    this.fields.forEach(field => {
      const validators = [];
      if (field.required) {
        validators.push(Validators.required);
      }

      const initialValue = this.getInitialValue(field.key);
      formConfig[field.key] = [
        { value: initialValue, disabled: this.isReadonly },
        validators
      ];
    });

    this.form = this.fb.group(formConfig);
  }

  private getInitialValue(fieldKey: string): string {
    if (!this.initialData) return '';
    
    // Mapear campos do formato address_* para o formato local
    const fieldMapping: { [key: string]: string } = {
      'cep': 'address_cep',
      'state': 'address_uf',
      'city': 'address_city',
      'neighborhood': 'address_neighborhood',
      'street': 'address_street',
      'number': 'address_number',
      'complement': 'address_complement'
    };

    const mappedKey = fieldMapping[fieldKey] || fieldKey;
    return (this.initialData as any)[mappedKey] || (this.initialData as any)[fieldKey] || '';
  }

  private setupFormListeners() {
    // Listener para mudanças no formulário
    const formChanges$ = this.form.valueChanges.pipe(
      debounceTime(300),
      distinctUntilChanged()
    );

    this.subscriptions.add(
      formChanges$.subscribe(value => {
        this.isFormDirty = true;
        this.dataChange.emit(this.mapToAddressData(value));
        this.formValidChange.emit(this.form.valid);
      })
    );

    // Listener específico para CEP
    const cepControl = this.form.get('cep');
    if (cepControl) {
      const cepChanges$ = cepControl.valueChanges.pipe(
        debounceTime(500),
        distinctUntilChanged()
      );

      this.subscriptions.add(
        cepChanges$.subscribe((cep: string) => {
          if (cep) {
            this.searchCep(cep);
          }
        })
      );
    }
  }

  searchCep(cep: string) {
    const cleanCep = cep.replace(/\D/g, "");
    if (cleanCep.length === 8) {
      this.isLoading = true;
      
      this.cepService.search(cleanCep).subscribe({
        next: (data: any) => {
          this.isLoading = false;
          if (!data.erro) {
            this.form.patchValue({
              state: data.uf || '',
              city: data.localidade || '',
              neighborhood: data.bairro || '',
              // complement: data.complemento || '',
              street: data.logradouro || ''
            });

            // Emitir evento de CEP encontrado
            this.cepSearched.emit({
              success: true,
              data: data,
              cep: cleanCep
            });
          } else {
            this.cepSearched.emit({
              success: false,
              error: 'CEP não encontrado',
              cep: cleanCep
            });
          }
        },
        error: (error) => {
          this.isLoading = false;
          console.error('Erro ao buscar CEP:', error);
          this.cepSearched.emit({
            success: false,
            error: 'Erro ao buscar CEP',
            cep: cleanCep
          });
        }
      });
    }
  }

  private mapToAddressData(formValue: any): AddressData {
    return {
      cep: formValue.cep || '',
      state: formValue.state || '',
      city: formValue.city || '',
      neighborhood: formValue.neighborhood || '',
      street: formValue.street || '',
      number: formValue.number || '',
      complement: formValue.complement || ''
    };
  }

  onSave() {
    if (this.form.valid) {
      const addressData = this.mapToAddressData(this.form.value);
      this.save.emit(addressData);
      this.isFormDirty = false;
    } else {
      this.markAllFieldsAsTouched();
    }
  }

  onCancel() {
    this.cancel.emit();
  }

  onReset() {
    this.form.reset();
    this.isFormDirty = false;
  }

  private markAllFieldsAsTouched() {
    Object.keys(this.form.controls).forEach(key => {
      this.form.get(key)?.markAsTouched();
    });
  }

  /**
   * Atualiza os dados do formulário externamente
   */
  updateData(data: AddressData) {
    const formValue = {
      cep: data.cep || '',
      state: data.state || '',
      city: data.city || '',
      neighborhood: data.neighborhood || '',
      street: data.street || '',
      number: data.number || '',
      complement: data.complement || ''
    };
    
    this.form.patchValue(formValue);
    this.isFormDirty = false;
  }

  /**
   * Obtém os dados atuais do formulário
   */
  getCurrentData(): AddressData {
    return this.mapToAddressData(this.form.value);
  }

  /**
   * Verifica se o formulário tem mudanças não salvas
   */
  hasUnsavedChanges(): boolean {
    return this.isFormDirty && this.form.dirty;
  }

  /**
   * Verifica se o formulário é válido
   */
  isValid(): boolean {
    return this.form.valid;
  }

  /**
   * Método público para testar busca de CEP
   */
  testCepSearch(cep: string): void {
    console.log(`🧪 Testando busca de CEP: ${cep}`);
    this.searchCep(cep);
  }
}
