import { Component, inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, Validators, FormArray, FormGroup, FormControl } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbProgressbarModule } from '@ng-bootstrap/ng-bootstrap';
import { UiCard } from '@app/components/ui-card';
import { PartnerConfigService } from '../services/partner-config.service';
import { CreatePartnerDto, PartnerCategory } from '../models/partners-config.model';
import { firstValueFrom } from 'rxjs';

@Component({
  selector: 'app-partner-config',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    NgIcon,
    NgbProgressbarModule,
    UiCard
  ],
  templateUrl: './config.html'
})
export class PartnerConfig implements OnInit {
  private fb = inject(FormBuilder);
  private PartnerConfigService = inject(PartnerConfigService);

  // Configuration wizard
  currentStep = 0;
  wizardSteps = [
    { id: 'company-info', icon: 'lucideBuilding', title: 'Informations Société', subtitle: 'Détails entreprise' },
    { id: 'contact-info', icon: 'lucideUser', title: 'Contact Principal', subtitle: 'Personne de contact' },
    { id: 'payment-config', icon: 'lucideCreditCard', title: 'Configuration Paiements', subtitle: 'Paramètres DCB' },
    { id: 'webhooks', icon: 'lucideWebhook', title: 'Webhooks', subtitle: 'Notifications et retours' },
    { id: 'review', icon: 'lucideCheckCircle', title: 'Validation', subtitle: 'Vérification finale' }
  ];

  configLoading = false;
  configError = '';
  configSuccess = '';

  // Formulaires
  partnerForm = this.fb.group({
    companyInfo: this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      legalName: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required]],
      website: [''],
      category: ['E_COMMERCE', [Validators.required]],
      country: ['CIV', [Validators.required]],
      currency: ['XOF', [Validators.required]],
      timezone: ['Africa/Abidjan', [Validators.required]]
    }),
    addressInfo: this.fb.group({
      street: ['', [Validators.required]],
      city: ['', [Validators.required]],
      state: ['', [Validators.required]],
      postalCode: ['', [Validators.required]],
      country: ['CIV', [Validators.required]]
    }),
    technicalContact: this.fb.group({
      name: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required]]
    }),
    paymentConfig: this.fb.group({
      commissionRate: [2.5, [Validators.required, Validators.min(0), Validators.max(100)]],
      dailyLimit: [1000000, [Validators.required, Validators.min(1000)]],
      transactionLimit: [50000, [Validators.required, Validators.min(100), Validators.max(500000)]],
      minAmount: [100, [Validators.required, Validators.min(1)]],
      maxAmount: [500000, [Validators.required, Validators.min(100)]]
    }),
    webhookConfig: this.fb.group({
      headerEnrichment: this.fb.group({
        url: ['', [Validators.pattern('https?://.+')]],
        method: ['POST'],
        headers: this.fb.array([])
      }),
      subscription: this.fb.group({
        onCreate: ['', [Validators.pattern('https?://.+')]],
        onRenew: ['', [Validators.pattern('https?://.+')]],
        onCancel: ['', [Validators.pattern('https?://.+')]],
        onExpire: ['', [Validators.pattern('https?://.+')]]
      }),
      payment: this.fb.group({
        onSuccess: ['', [Validators.pattern('https?://.+')]],
        onFailure: ['', [Validators.pattern('https?://.+')]],
        onRefund: ['', [Validators.pattern('https?://.+')]]
      }),
      authentication: this.fb.group({
        onSuccess: ['', [Validators.pattern('https?://.+')]],
        onFailure: ['', [Validators.pattern('https?://.+')]]
      })
    })
  });

  // Données partagées
  countries = [
    { code: 'CIV', name: 'Côte d\'Ivoire' },
    { code: 'SEN', name: 'Sénégal' },
    { code: 'CMR', name: 'Cameroun' },
    { code: 'GHA', name: 'Ghana' },
    { code: 'NGA', name: 'Nigeria' }
  ];

  categories = [
    { value: 'E_COMMERCE', label: 'E-Commerce' },
    { value: 'GAMING', label: 'Jeux & Gaming' },
    { value: 'ENTERTAINMENT', label: 'Divertissement' },
    { value: 'UTILITIES', label: 'Services Publics' },
    { value: 'DIGITAL_CONTENT', label: 'Contenu Digital' },
    { value: 'SERVICES', label: 'Services' },
    { value: 'OTHER', label: 'Autre' }
  ];

  currencies = [
    { code: 'XOF', name: 'Franc CFA' },
    { code: 'EUR', name: 'Euro' },
    { code: 'USD', name: 'Dollar US' }
  ];

  timezones = [
    { value: 'Africa/Abidjan', label: 'Abidjan (GMT)' },
    { value: 'Africa/Lagos', label: 'Lagos (WAT)' },
    { value: 'Africa/Johannesburg', label: 'Johannesburg (SAST)' }
  ];

  httpMethods = [
    { value: 'GET', label: 'GET' },
    { value: 'POST', label: 'POST' }
  ];

  ngOnInit() {}

  // Navigation du wizard
  get progressValue(): number {
    return ((this.currentStep + 1) / this.wizardSteps.length) * 100;
  }

  nextStep() {
    if (this.currentStep < this.wizardSteps.length - 1 && this.isStepValid(this.currentStep)) {
      this.currentStep++;
    }
  }

  previousStep() {
    if (this.currentStep > 0) {
      this.currentStep--;
    }
  }

  goToStep(index: number) {
    if (this.isStepAccessible(index)) {
      this.currentStep = index;
    }
  }

  isStepAccessible(index: number): boolean {
    if (index === 0) return true;
    
    for (let i = 0; i < index; i++) {
      if (!this.isStepValid(i)) {
        return false;
      }
    }
    return true;
  }

  isStepValid(stepIndex: number): boolean {
    switch (stepIndex) {
      case 0: // Company Info
        return this.companyInfo.valid;
      case 1: // Contact Info
        return this.addressInfo.valid && this.technicalContact.valid;
      case 2: // Payment Config
        return this.paymentConfig.valid;
      case 3: // Webhooks (toujours valide car optionnel)
        return true;
      case 4: // Review
        return this.partnerForm.valid;
      default:
        return false;
    }
  }

  // Gestion des headers dynamiques - CORRECTION ICI
  get headerEnrichmentHeaders(): FormArray {
    return this.headerEnrichment.get('headers') as FormArray;
  }

  // Méthode pour obtenir un FormControl sécurisé - NOUVELLE MÉTHODE
  getHeaderControl(header: any, field: string): FormControl {
    return header.get(field) as FormControl;
  }

  addHeader() {
    const headerGroup = this.fb.group({
      key: ['', Validators.required],
      value: ['', Validators.required]
    });
    this.headerEnrichmentHeaders.push(headerGroup);
  }

  removeHeader(index: number) {
    this.headerEnrichmentHeaders.removeAt(index);
  }

  // Soumission du formulaire
  async submitForm() {
    if (this.partnerForm.valid) {
      this.configLoading = true;
      this.configError = '';

      try {
        const formData = this.partnerForm.value;

        const createPartnerDto: CreatePartnerDto = {
          name: this.safeString(formData.companyInfo?.name) || '',
          legalName: this.safeString(formData.companyInfo?.legalName) || '',
          email: this.safeString(formData.companyInfo?.email) || '',
          phone: this.safeString(formData.companyInfo?.phone) || '',
          website: this.safeString(formData.companyInfo?.website) || '',
          category: (this.safeString(formData.companyInfo?.category) as PartnerCategory) || 'OTHER',
          country: this.safeString(formData.companyInfo?.country) || 'CIV',
          currency: this.safeString(formData.companyInfo?.currency) || 'XOF',
          timezone: this.safeString(formData.companyInfo?.timezone) || 'Africa/Abidjan',
          commissionRate: this.safeNumber(formData.paymentConfig?.commissionRate) || 0,
          dailyLimit: this.safeNumber(formData.paymentConfig?.dailyLimit) || 0,
          transactionLimit: this.safeNumber(formData.paymentConfig?.transactionLimit) || 0,
          minAmount: this.safeNumber(formData.paymentConfig?.minAmount) || 0,
          maxAmount: this.safeNumber(formData.paymentConfig?.maxAmount) || 0,
        };

        const response = await firstValueFrom(
          this.PartnerConfigService.createPartnerConfig(createPartnerDto)
        );

        if (response.success && response.data) {
          this.configSuccess = `Partenaire créé avec succès! ID: ${response.data.id}`;
          this.partnerForm.reset();
          this.currentStep = 0;
        } else {
          this.configError = response.error || 'Erreur lors de la création du partenaire';
        }

      } catch (error) {
        this.configError = 'Erreur lors de la création du partenaire';
        console.error('Error creating partner:', error);
      } finally {
        this.configLoading = false;
      }
    } else {
      this.configError = 'Veuillez corriger les erreurs dans le formulaire';
      this.markAllFieldsAsTouched();
    }
  }

  // Méthodes utilitaires
  private safeString(value: string | null | undefined): string {
    return value || '';
  }

  private safeNumber(value: number | null | undefined): number {
    return value || 0;
  }

  private markAllFieldsAsTouched() {
    Object.keys(this.partnerForm.controls).forEach(key => {
      const control = this.partnerForm.get(key);
      if (control instanceof FormGroup) {
        Object.keys(control.controls).forEach(subKey => {
          control.get(subKey)?.markAsTouched();
        });
      } else {
        control?.markAsTouched();
      }
    });
  }

  // Getters pour les formulaires - CORRECTION ICI (suppression des ?)
  get companyInfo() {
    return this.partnerForm.get('companyInfo') as FormGroup;
  }

  get addressInfo() {
    return this.partnerForm.get('addressInfo') as FormGroup;
  }

  get technicalContact() {
    return this.partnerForm.get('technicalContact') as FormGroup;
  }

  get paymentConfig() {
    return this.partnerForm.get('paymentConfig') as FormGroup;
  }

  get webhookConfig() {
    return this.partnerForm.get('webhookConfig') as FormGroup;
  }

  get headerEnrichment() {
    return this.webhookConfig.get('headerEnrichment') as FormGroup;
  }

  get subscription() {
    return this.webhookConfig.get('subscription') as FormGroup;
  }

  get payment() {
    return this.webhookConfig.get('payment') as FormGroup;
  }

  get authentication() {
    return this.webhookConfig.get('authentication') as FormGroup;
  }
}