import { Component, ElementRef, QueryList, ViewChildren } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { JobListing, JobListingSkills } from 'app/models/JobListing';
import { Authentication } from 'app/services/Authentication';

@Component({
  selector: 'main-jobs-editor',
  templateUrl: './jobeditor.component.html',
  styleUrls: [ './jobeditor.component.css' ],
  imports: [ FormsModule, CommonModule, RouterModule ]
})
export class JobEditorComponent {
  public ErrorMsg: string = "";

  @ViewChildren('step') formSteps!: QueryList<ElementRef<HTMLDivElement>>;
  currentStep: number = 0;

  public Listing: JobListing = new JobListing();
  public isNewListing: boolean = true;

  public mode: string = "";

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication ) {
    this.title.setTitle("Jobs - Editor | BoredCareers");
    if (!auth.isLoggedIn){
      router.navigate(["/"]);
    }
  }

  ngOnInit(){
    this.route.queryParams.subscribe(params => {
      const CompanyID = params['CompanyID'] ? +params['CompanyID'] : null;
      const JobID = params['JobID'] ? +params['JobID'] : null;
      if (CompanyID !== null && JobID !== null){
        this.router.navigate([""]);
      }else if (CompanyID !== null ){
        this.mode = "new";
        this.Listing.companyID = CompanyID;
      }else if(JobID !== null){
        this.mode = "edit";
        this.Listing.id = JobID;
        this.isNewListing = false;
      }else if (CompanyID === null && JobID === null){
        this.router.navigate([""]);
      }

      if (this.mode === "edit") {
        this.http.get<JobListing>("api/joblisting/" + JobID).subscribe({
          next: data => {
            data.skills.forEach(element => {
              element.trackUUID = crypto.randomUUID();
            });
            this.Listing = data;
          },
          error: err => {
            this.ErrorMsg = err.error;
          }
        });
      }
    });
  }

  ngAfterViewInit(){
    this.formSteps.changes.subscribe(() => {
      this.updateUI();
    });
    this.updateUI();
  }

  updateUI(){
    this.formSteps.forEach((step: ElementRef<HTMLDivElement>, i: number) => {
      if (i === this.currentStep) {
        step.nativeElement.style.left = '0%';
      } else if (i < this.currentStep) {
        step.nativeElement.style.left = '-100%';
      } else {
        step.nativeElement.style.left = '100%';
      }
    });
  }

  addSkill(){
    this.Listing.skills.push(new JobListingSkills);
  }

  remSkill(self: JobListingSkills){
    for(let i=0; i<this.Listing.skills.length; i++){
      let cur = this.Listing.skills[i];
      if (cur.trackUUID === self.trackUUID){
        this.Listing.skills.splice( i, 1 );
        break;
      }
    }
  }

  nextStep(){
    this.currentStep += 1;
    this.updateUI();
  }

  prevStep(){
    this.currentStep -= 1;
    this.updateUI();
  }

  SubmitForm(jobListing: JobListing){
    this.http.post("api/joblisting", jobListing).subscribe({
      next: data => {
        this.router.navigate(["/company"]);
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

}