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 { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ValidationError } from 'src/app/models/fnd/ValidationError';
import { Visa_applicationservice } from '../Visa_application.service';
@Component({
  selector: 'app-editstepper',
  templateUrl: './editstepper.component.html',
  styleUrls: ['./editstepper.component.scss']
})
export class EditstepperComponent implements OnInit {
  updated = false;
  // college: College;
  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 },
    step2: { state: "not-started", open: false, failed: false },
  };


  public entryForm: FormGroup;
  submitted = false;
  rowSelected: any = {};
  modalcomplete = false;

  constructor(private mainService: Visa_applicationservice,

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

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

    this.entryForm = this._fb.group({
      name: [null],

      description: [null],

      active: [false],

      visa_entry_type: [null],

      visa_duration: [null],

      visa_processing: [null],

      travel_start_date: [null],

      travel_end_date: [null],

      passport_number: [null, [Validators.required]],

      passport_issue_date: [null],

      passport_expiry_date: [null],

      email: [null],

      phone_number: ['+91'],

      birth_place: [null],

      date_of_birth: [null],

      gender: [null],

      profession: [null],

      visa_cost: [null, { updateOn: 'blur' }],

      referrer: [null],

      nationality: [null],

      supplier: [null],

      agent: [null],

    });


    this.getallvisa_entry_type();

    this.getallvisa_duration();

    this.getallvisa_processing();

    this.getallgender();

    this.getallreferrer();

    this.getallnationality();

    this.getallsupplier();

    this.getallagent();

  }

  // 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 ",
    }
  }
  getById(id: number) {
    // this.mainService.getBywfId(id).subscribe(
    //   (data) => {
    //     this.college = data;
    //   },
    //   (err) => {
    //     console.log(err);
    //   }
    // );
    // this.currentservice.getById(id).subscribe(
    //   (data) => {
    //     this.student = data;

    //     var current = JSON.parse(data.current_json);
    //     this.timelineStyle = current;
    //     console.log("data", data);
    //   },
    //   (err) => {
    //     console.log(err);
    //   }
    // );


  }


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

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


      return;
    }
    this.onCreate();
  }

  onCreate() {
    this.mainService.create(this.entryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

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


        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.entryForm.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 },
      step2: { 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);

    // this.mainService.update(this.id, this.college, this.stringJson).subscribe(
    //   (data) => {
    //     console.log(data);
    //   },

    // );
  }

  onFileUpload(): void {

    for (let i = 0; i < this.selectedfileupload_field.length; i++) {

      this.mainService.uploadDocument(this.customerId, 'visa order', this.selectedfileupload_field[i]).subscribe(uploaddata => {
        console.log(uploaddata);

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


        if (uploaddata || uploaddata.status >= 200 && uploaddata.status <= 299) {
          // alert('File uploaded successfully!');
          this.toastr.success("File uploaded 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.selectedFile = null;
  }


  filePreviewfileupload_field: string | ArrayBuffer | null = null;
  FileDatafileupload_field: { uploadedfile_name?: any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
  selectedfileupload_field: File[] = [];
  public onFileChangedfileupload_field(event, index) {
    const files = event.target.files;
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      this.FileDatafileupload_field[index].uploadedfile_name = files[i].name;
      this.selectedfileupload_field.push(files[i]);
      if (file.type.startsWith('file/')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          // Set the file preview source
          const filePreview = e.target?.result as string;
          this.FileDatafileupload_field[index] = {
            ...this.FileDatafileupload_field[index], // Preserve existing properties
            filePreview: filePreview // Update only the filePreview property
          };
        };
        reader.readAsDataURL(file);
      }
    }
  }
  onAddLinesfileupload_field() {
    this.FileDatafileupload_field.push({
      uploadedfile_name: "",
      filePreview: "",
      // f3: "",
    });
  }
  deleteRowfileupload_field(index, id) {
    this.FileDatafileupload_field.splice(index, 1);

    if (id) {
      this.mainService.uploadfiledeletefileupload_field(id).subscribe(data => {
        console.log(data);
      })
    }
  }

  updategender(gender: string): void {
    this.entryForm.get('gender').setValue(gender);
  }

  updategenderEdit(gender: string): void { this.rowSelected.gender = gender }









  rsModaldescription = false;
  goToReplaceStringdescription(row) {
    this.rowSelected = row; this.rsModaldescription = true;
  }



  selectvisa_entry_type;
  getallvisa_entry_type() {
    this.mainService.getAllvisa_entry_type().subscribe(data => {
      this.selectvisa_entry_type = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectvisa_duration;
  getallvisa_duration() {
    this.mainService.getAllvisa_duration().subscribe(data => {
      this.selectvisa_duration = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectvisa_processing;
  getallvisa_processing() {
    this.mainService.getAllvisa_processing().subscribe(data => {
      this.selectvisa_processing = data;
      console.log('visa processing ', data);
    }, (error) => { console.log(error); });
  }

  isValidemail(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);
  }





  selectgender;
  getallgender() {
    this.mainService.getAllgender().subscribe(data => {
      this.selectgender = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }



  //currency  field start
  formatCurrencyvisa_cost() {
    // Format the currency with two decimal places    
    this.rowSelected.visa_cost = Number(this.rowSelected.visa_cost).toFixed(2);
    // Remove commas from the formatted currency   
    this.rowSelected.visa_cost = this.rowSelected.visa_cost?.replace(/,/g, '');
  }
  //currency  field end

  selectreferrer;
  getallreferrer() {
    this.mainService.getAllreferrer().subscribe(data => {
      this.selectreferrer = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectnationality;
  getallnationality() {
    this.mainService.getAllnationality().subscribe(data => {
      this.selectnationality = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectsupplier;
  getallsupplier() {
    this.mainService.getAllsupplier().subscribe(data => {
      this.selectsupplier = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectagent;
  getallagent() {
    this.mainService.getAllagent().subscribe(data => {
      this.selectagent = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

}
