import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { StorageService } from 'src/app/core/services/storage.service';
import { DataService } from 'src/app/core/services/data.service';
import { ToastService } from 'src/app/services/toast.service';
import { FormSection, EntityBadge } from 'src/app/components/dynamic-form/harmonized-create-view.component';

@Component({
  selector: 'app-harmonized-create',
  templateUrl: './harmonized-create.page.html',
  styleUrls: ['./harmonized-create.page.scss']
})
export class HarmonizedCreatePageComponent implements OnInit {
  // Form data
  form!: FormGroup;
  formData: any[] = [];
  formSections?: FormSection[];

  // Entity configuration
  entityTitle: string = '';
  entitySubtitle: string = '';
  entityBadges?: EntityBadge[];

  // State
  isEdit: boolean = false;
  isLoading: boolean = false;
  editId?: string;

  // Module information
  moduleName: string = '';
  domaine: string = '';
  metadatas: any[] = [];

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private fb: FormBuilder,
    private storage: StorageService,
    private dataService: DataService,
    private toast: ToastService
  ) {}

  async ngOnInit() {
    // Get module and domain info from route or localStorage
    await this.initializeModuleInfo();

    // Check if edit mode
    this.editId = this.route.snapshot.paramMap.get('id') || undefined;
    this.isEdit = !!this.editId;

    // Load form configuration
    await this.loadFormConfiguration();

    // Setup form
    this.setupForm();

    // Setup entity configuration
    this.setupEntityConfiguration();

    // Load data for edit mode
    if (this.isEdit && this.editId) {
      await this.loadEditData();
    }
  }

  private async initializeModuleInfo() {
    // Get from route params first
    const moduleFromRoute = this.route.snapshot.paramMap.get('module');
    const domaineFromRoute = this.route.snapshot.paramMap.get('domaine');

    if (moduleFromRoute && domaineFromRoute) {
      this.moduleName = moduleFromRoute;
      this.domaine = domaineFromRoute;
    } else {
      // Fallback to localStorage
      const dd = this.storage.getItem("__domaineDD");
      if (dd) {
        const domaineData = dd ? JSON.parse(dd) : {};
        this.moduleName = domaineData?.modulename || '';
        this.domaine = domaineData?.domaine || '';
      }
    }
  }

  private async loadFormConfiguration() {
    try {
      this.isLoading = true;

      // Load metadatas for the module (same logic as ProjectsComponent)
      const metadatasResponse = await this.dataService.getAll(this.domaine, `${this.moduleName}/metadatas`).toPromise();
      this.metadatas = metadatasResponse as any[];

      // Convert metadatas to formData format
      this.convertMetadatasToFormData();

    } catch (error) {
      console.error('Error loading form configuration:', error);
      this.toast.showError('Erreur lors du chargement de la configuration');
    } finally {
      this.isLoading = false;
    }
  }

  private convertMetadatasToFormData() {
    this.formData = this.metadatas
      .filter(metadata => this.shouldShowField(metadata))
      .sort((a, b) => (a.sequencecreate || 0) - (b.sequencecreate || 0))
      .map(metadata => ({
        controlName: metadata.name,
        controlType: this.getControlType(metadata.type),
        valueType: this.getValueType(metadata.type),
        placeholder: metadata.displayName,
        validators: {
          required: metadata.mandatory === 1 || metadata.mandatory === true
        },
        options: metadata.options?.map((opt: any) => ({
          value: opt.value,
          optionName: opt.value
        })) || []
      }));

    // Generate form sections based on blocs
    this.generateFormSections();
  }

  private shouldShowField(metadata: any): boolean {
    // Show field if bloc_enabled is true and it's not a system field
    return metadata.bloc_enabled === 1 &&
           !['id', 'created_at', 'updated_at', 'modified_by', 'is_deleted'].includes(metadata.name);
  }

  private getControlType(metadataType: string): string {
    switch (metadataType) {
      case 'string':
      case 'currency':
      case 'double':
      case 'integer':
      case 'datetime':
      case 'date':
        return 'text';
      case 'text':
        return 'textarea';
      case 'picklist':
        return 'select';
      default:
        return 'text';
    }
  }

  private getValueType(metadataType: string): string {
    switch (metadataType) {
      case 'string':
      case 'text':
        return 'text';
      case 'currency':
      case 'double':
      case 'integer':
        return 'number';
      case 'datetime':
        return 'datetime-local';
      case 'date':
        return 'date';
      default:
        return 'text';
    }
  }

  private setupForm() {
    const formControls: any = {};

    this.formData.forEach(field => {
      const validators = [];
      if (field.validators.required) {
        validators.push(Validators.required);
      }

      formControls[field.controlName] = ['', validators];
    });

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

  private setupEntityConfiguration() {
    if (this.isEdit) {
      this.entityTitle = `Modifier ${this.getModuleLabel()}`;
      this.entitySubtitle = `Modification de l'élément • ID: ${this.editId}`;
      this.entityBadges = [
        { label: 'Modification', icon: 'edit', type: 'warning' }
      ];
    } else {
      this.entityTitle = `Créer ${this.getModuleLabel()}`;
      this.entitySubtitle = `Création d'un nouvel élément • Statut: Brouillon`;
      this.entityBadges = [
        { label: 'Nouveau', icon: 'add', type: 'default' }
      ];
    }
  }

  private getModuleLabel(): string {
    // Convert module name to user-friendly label
    switch (this.moduleName?.toLowerCase()) {
      case 'accounts':
        return 'un compte';
      case 'projects':
        return 'un projet';
      case 'pnr':
        return 'un PNR';
      default:
        return `un ${this.moduleName}`;
    }
  }

  private generateFormSections() {
    // Group metadatas by bloc
    const blocGroups = new Map<string, any[]>();

    this.metadatas
      .filter(metadata => this.shouldShowField(metadata))
      .sort((a, b) => (a.sequencecreate || 0) - (b.sequencecreate || 0))
      .forEach(metadata => {
        const bloc = metadata.bloc || 'Autres';
        if (!blocGroups.has(bloc)) {
          blocGroups.set(bloc, []);
        }
        blocGroups.get(bloc)!.push(metadata);
      });

    // Convert to FormSection array
    this.formSections = Array.from(blocGroups.entries()).map(([blocName, metadatas]) => {
      // Determine icon based on bloc name
      const icon = this.getBlocIcon(blocName);

      return {
        title: blocName,
        icon: icon,
        columns: '2' as '2',
        fields: metadatas.map(m => m.name)
      };
    });
  }

  private getBlocIcon(blocName: string): string {
    const blocLower = blocName.toLowerCase();
    if (blocLower.includes('général') || blocLower.includes('general')) return 'info';
    if (blocLower.includes('financ')) return 'attach_money';
    if (blocLower.includes('coordonnée') || blocLower.includes('contact')) return 'contacts';
    if (blocLower.includes('autre')) return 'more_horiz';
    return 'description';
  }

  private async loadEditData() {
    try {
      this.isLoading = true;

      const data = await this.dataService.getById(this.domaine, this.moduleName, this.editId!).toPromise();

      // Populate form with existing data
      if (data) {
        this.form.patchValue(data);
      }

    } catch (error) {
      console.error('Error loading edit data:', error);
      this.toast.showError('Erreur lors du chargement des données');
    } finally {
      this.isLoading = false;
    }
  }

  async onSave(formValue: any) {
    try {
      this.isLoading = true;

      let result;
      if (this.isEdit && this.editId) {
        result = await this.dataService.update(this.domaine, this.moduleName, this.editId, formValue).toPromise();
        this.toast.showSuccess('Élément modifié avec succès');
      } else {
        result = await this.dataService.create(this.domaine, this.moduleName, formValue).toPromise();
        this.toast.showSuccess('Élément créé avec succès');
      }

      // Navigate back to list
      this.router.navigate(['../'], { relativeTo: this.route });

    } catch (error) {
      console.error('Error saving:', error);
      this.toast.showError('Erreur lors de la sauvegarde');
    } finally {
      this.isLoading = false;
    }
  }

  onCancel() {
    // Navigate back to list
    this.router.navigate(['../'], { relativeTo: this.route });
  }

  onSaveAndContinue(formValue: any) {
    // Save and reset form for new entry
    this.onSave(formValue).then(() => {
      if (!this.isEdit) {
        this.form.reset();
        this.toast.showSuccess('Formulaire réinitialisé pour une nouvelle saisie');
      }
    });
  }
}