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 } from 'app/models/JobListing';
import { Authentication } from 'app/services/Authentication';
import { Company, Employee } from 'app/models/Company';

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

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

  public employeeOfList: Employee[] = [];
  public selectedCompany: Company = new Company;

  public newListing: JobListing = new JobListing();
  public ErrorMsg: string = "";

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication ) {
    this.title.setTitle("Jobs - Editor | BoredCareers");

    this.http.get<Employee[]>("api/employee").subscribe({
      next: empOf => {
        if (empOf.length === 0){
          router.navigate(["company/connect"]);
        }
        this.employeeOfList = empOf;
      },
      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%';
      }
    });
  }

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

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

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

}