import { Component, OnInit } from '@angular/core';


import { ToastrService } from 'ngx-toastr';
import { ActivatedRoute, Router } from '@angular/router';
import { College } from 'src/app/models/fnd/play';
import { student } from 'src/app/models/fnd/Studentadd';
import { AbstractControl,FormArray, FormBuilder, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { ValidationError } from 'src/app/models/fnd/ValidationError';
import { steperservice } from './steper.service';
declare var JsBarcode: any;
  @Component({
  selector: 'app-editstepper',
  templateUrl: './steper.component.html',
  styleUrls: ['./steper.component.scss']
})
export class steperComponent implements OnInit {
  updated = false;
  stringJson: any;
  customerId: string = '';
  selectedFile!: File;
  fileName = '';

  id: number;
  errorFields: ValidationError[] = [];
  appToUpdate: College = null;
  trained = false;

  json: string = "";
  luisApp =
    {
      name: '',
      created: 1,
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,

    };
  // Layout direction changing
  layout = {
    direction: "vertical",
    block1: "clr-col-lg-3 clr-col-12 ",
    block2: "clr-col-lg-9 clr-col-12 ",
  };

  timelineStyle = { 
 step0: { state: "current", open: true, failed: false }, 
    step1: { state: "not-started", open: false, failed: false },
};
public Customer_informationentryForm: FormGroup;
  submitted = false;
  rowSelected: any = {};
  modalcomplete = false;

  constructor( 
private mainService: steperservice,

private Customer_information_fb: FormBuilder, 
private router: Router,
 private route: ActivatedRoute,
    private toastr: ToastrService,
  ) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.params["id"];
    console.log("update with id = ", this.id);


 this.Customer_informationentryForm = this.Customer_information_fb.group({ 
customer_name : [null],

contact_person : [null],

email_address : [null],

phone_number: ['+91'],

customer_address : [null],

deployment_type : [null],

  
 
compressed_air__gas_monotoring:[false],
   

 
active_energy:[false],
   

 
dg_monitoring___with_fuel:[false],
   

 
dg_monitoring___without_fuel:[false],
   

 
ups_monitoring:[false],
   

 
apfc_panel_monitoring:[false],
   

 
busbar_monitoring:[false],
   

 
water_management__water_quality:[false],
   

 
lt_panel_monitoring:[false],
   

 
ht_panel_monitoring:[false],
   

 
compress_air___lpg_o2_n2_co2:[false],
   

 
water_management__stp_etp:[false],
   

 
water_management___water_monitoring:[false],
   


product_selection: this.Customer_information_fb.array([this.initLinesForm()]),


  });
















 const stepId = this.id; // or from route/query/etc
 
    this.getResolvedDataFromStepper(stepId).subscribe(res => {
      console.log('response get ', res);

      if (res === null) {
        this.showEmptyForm();
      } else {
 if (res['Customer_information']) {
 
 this.prefillorder_estimationForm(res['Customer_information']);
        }
}
    });

  }
showEmptyForm(): void {
    console.log('No config found. Showing empty form.');
    // You can choose to show one or both based on some logic

 this.Customer_informationentryForm.reset();
  }  prefillorder_estimationForm(data: any): void {

    console.log(' order_estimation data ', data)
    this.Customer_informationentryForm.patchValue({
      id: data.id || '',
customer_name: data.customer_name || '',

contact_person: data.contact_person || '',

email_address: data.email_address || '',

phone_number: data.phone_number || '',

customer_address: data.customer_address || '',

deployment_type: data.deployment_type || '',

 
 

lt_panel_monitoring: data.lt_panel_monitoring || '',
 

 

active_energy: data.active_energy || '',
 

 

dg_monitoring___with_fuel: data.dg_monitoring___with_fuel || '',
 

 

dg_monitoring___without_fuel: data.dg_monitoring___without_fuel || '',
 

 

ups_monitoring: data.ups_monitoring || '',
 

 

water_management__water_quality: data.water_management__water_quality || '',
 

 

apfc_panel_monitoring: data.apfc_panel_monitoring || '',
 

 

busbar_monitoring: data.busbar_monitoring || '',
 

 

ht_panel_monitoring: data.ht_panel_monitoring || '',
 

 

water_management__stp_etp: data.water_management__stp_etp || '',
 

 

compressed_air__gas_monotoring: data.compressed_air__gas_monotoring || '',
 

 

compress_air___lpg_o2_n2_co2: data.compress_air___lpg_o2_n2_co2 || '',
 

 

water_management___water_monitoring: data.water_management___water_monitoring || '',
 




product_selection: data.product_selection || '',

    });
  }
 getResolvedDataFromStepper(id: number): Observable<any> {
    console.log('get step config');

    return new Observable(observer => {
      this.mainService.gettabledata(id).subscribe(configList => {
        if (!configList || configList.length === 0) {
          console.log('empty config');
          observer.next(null);
          observer.complete();
          return;
        }

        const results: { [key: string]: any } = {};
        let processed = 0;

        configList.forEach(config => {
          const { table_name, table_id } = config;

          this.getByTableNameAndId(table_name, table_id).subscribe(data => {

            console.log('data is ', data);
            results[table_name] = data;

            processed++;
            if (processed === configList.length) {
              observer.next(results);  // emit combined data
              observer.complete();
            }

          }, error => {
            console.error(`Error loading data for table ${table_name}`, error);
            processed++;
            if (processed === configList.length) {
              observer.next(results);  // continue with what we have
              observer.complete();
            }
          });
        });

      }, error => {
        console.error("Error loading stepper config", error);
        observer.error(error);
      });
    });
  }



  getByTableNameAndId(tableName: string, id: number): Observable<any> {

    switch (tableName) {
   case 'Customer_information':
        return this.mainService.getCustomer_informationById(id);// aur bhi cases agar naye table add ho to
      default:
        throw new Error(`Unknown table name: ${tableName}`);
    }
  }
  // Change to Horizontal Layout
  changeToHorizonTal() {
    this.layout = {
      direction: "horizontal",
      block1: "clr-col-lg-12 clr-col-12 height container",
      block2: "clr-col-lg-12 clr-col-12 container",
    }
  }
  // Change to Vertical Layout
  changeToVertical() {
    this.layout = {
      direction: "vertical",
      block1: "clr-col-lg-3 clr-col-12 ",
      block2: "clr-col-lg-9 clr-col-12 ",
    }
  }



  onorder_estimationSave() {
    console.log('Form Submitted:', this.Customer_informationentryForm.value);
    this.submitted = true;
    if (this.Customer_informationentryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.Customer_informationentryForm.controls).forEach(field => {
        const control = this.Customer_informationentryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.onorder_estimationCreate();
  }

  onorder_estimationCreate() {
















    this.mainService.createCustomer_information(this.Customer_informationentryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Customer_information';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);

















      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    this.rowSelected = this.Customer_informationentryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  onnext() {
    this.router.navigate(["../../main/workflow"], { relativeTo: this.route });
  }
  reset() {
    this.json = "";
    this.luisApp =
    {
      name: '',
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,
      created: 1,

    };

    this.timelineStyle = {
      step0: { state: "current", open: true, failed: false },
      step1: { state: "not-started", open: false, failed: false },
 };
  }
  current() {
    console.log(this.timelineStyle)
    this.stringJson = JSON.stringify(this.timelineStyle);
    console.log("String json object :", this.stringJson);

  }




isValidemail_address(email: string): boolean {
						 const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
						    return emailPattern.test(email);   }

isValidPhone_number(phone: string): boolean {
  const phonePattern = /^(\+[1-9][0-9]{0,2})?[1-9][0-9]{9}$/;
  return phonePattern.test(phone);
}

rsModalcustomer_address = false;   
goToReplaceStringcustomer_address(row){
this.rowSelected = row;     this.rsModalcustomer_address  =true;   }





















// one to many start
 initLinesForm() {    return this.Customer_information_fb.group({ 


 	
 type: [null],
 

 	
 price: [null],
 

 	
 total: [null],
 

 	
 manufacturer: [null],
 

 	
 product: [null],
 

 	
 quantity: [null],
 

 	
 name: [null],
 


});  }  
get controls() {return (this.Customer_informationentryForm.get("product_selection") as FormArray).controls;  }
onAddLines() {
(<FormArray>this.Customer_informationentryForm.get("product_selection")).push(this.initLinesForm());  }
onRemoveLines(index: number) {
(<FormArray>this.Customer_informationentryForm.get("product_selection")).removeAt(index);  }
 oneditLines() {    this.components.push({ 

 
type: "",
 

 
price: "",
 

 
total: "",
 

 
manufacturer: "",
 

 
product: "",
 

 
quantity: "",
 

 
name: "",
 


	  });  }  
 deleteRow(index) {
 this.components.splice(index, 1); 
 }  
		 components;
 // one to many end 

// updateaction
}















