import { Component, ElementRef, HostListener, 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 { Authentication } from 'app/services/Authentication';
import { Company } from 'app/models/Company';
import { Validation } from 'app/services/Validation';

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

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

  public newListing: Company = new Company();
  public isNewCompany: boolean = true;
  public ErrorMsg: string = "";
  MaxFileMB: number = 3;

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

  ngOnInit(){
    this.route.queryParams.subscribe(params => {
      const CompanyID = params['CompanyID'] ? +params['CompanyID'] : null;
      if (CompanyID !== null){
        this.http.get<Company>("api/company?CompanyID=" + CompanyID).subscribe({
          next: data => {
            this.newListing = data;
            this.isNewCompany = false;
          },
          error: err => {
            this.ErrorMsg = err.error;
          }
        });
      }
    });
  }

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

  validatePhone(input: string){
    let result = this.validator.validatePhoneNumber(input);
    this.newListing.phone = result[1];
  }

  validateEmail(input: string){
    let result = this.validator.validateEmail(input);
    this.newListing.email = result[1];
  }

  validateURL(input: string){
    let result = this.validator.validateURL(input);
    this.newListing.websiteURL = result[1];
  }

  @HostListener('window:keydown', ['$event'])
  handleGlobalKeyDown(event: KeyboardEvent){
    if ( event.key === 'Tab' ){
      event.preventDefault();
    }
  }

  updateUI(subItem: number){
    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%';
      }
    });
    setTimeout(() => {
      (this.formSteps.get(this.currentStep)?.nativeElement.querySelectorAll('.input-field')[subItem] as HTMLElement)?.focus();
    }, 500);
  }

  selectedFile: File | null = null;
  onFileSelected(event: Event){
    const fileInput = event.target as HTMLInputElement;
    this.selectedFile = null;

    if (!fileInput.files?.length){
      return;
    }

    let file = fileInput.files[0];
    if (file.size > this.MaxFileMB * 1024 * 1024){
      this.ErrorMsg = "File exceeds max file size of 16MB";
      return;
    }
    // No issues add file to the list
    this.selectedFile = file;

    const reader = new FileReader();
    reader.onload= () => {
      this.newListing.logo = reader.result as string;
    }
    reader.readAsDataURL(file);
  }

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

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

  isNullOrEmpty(str: string | null | undefined): boolean {
    return !str || str.trim().length === 0;
  }

  focusFrame(frameNum: number, subItem: number): void {
    this.currentStep = frameNum;
    this.updateUI(subItem);
  }

  PostNewCompany(company: Company){

    if (this.isNullOrEmpty(company.name)){
      this.ErrorMsg = "Comany name is blank";
      this.focusFrame(0, 0);
      return;
    }

    if (this.isNullOrEmpty(company.websiteURL)){
      this.ErrorMsg = "Website URL is blank";
      this.focusFrame(1, 0);
      return;
    }

    var urlIsValid = this.validator.validateURL(company.websiteURL);
    if (urlIsValid[0] == false){
      this.ErrorMsg = urlIsValid[1];
      this.focusFrame(1, 0);
      return;
    }

    if (this.isNullOrEmpty(company.logo)){
      this.ErrorMsg = "Logo is blank";
      this.focusFrame(2, 0);
      return;
    }

    if (this.isNullOrEmpty(company.email)){
      this.ErrorMsg = "Email is blank";
      this.focusFrame(3, 0);
      return;
    }

    var emailIsValid = this.validator.validateEmail(company.email);
    if (emailIsValid[0] == false){
      this.ErrorMsg = emailIsValid[1];
      this.focusFrame(3, 0);
      return;
    }

    if (this.isNullOrEmpty(company.phone)){
      this.ErrorMsg = "Phone number is blank";
      this.focusFrame(3, 1);
      return;
    }

    if (this.validator.validatePhoneNumber(company.phone)[0] == false){
      this.ErrorMsg = "Phone number is invalid";
      this.focusFrame(3, 1);
      return;
    }

    if (this.isNullOrEmpty(company.city)){
      this.ErrorMsg = "City is blank";
      this.focusFrame(4, 0);
      return;
    }

    if (this.isNullOrEmpty(company.country)){
      this.ErrorMsg = "Country is blank";
      this.focusFrame(4, 1);
      return;
    }

    if (this.isNullOrEmpty(company.stateOrRegion)){
      this.ErrorMsg = "State or Region is blank";
      this.focusFrame(4, 2);
      return;
    }

    if (this.isNullOrEmpty(company.postalCode)){
      this.ErrorMsg = "Postal Code is blank";
      this.focusFrame(4, 3);
      return;
    }

    if (this.isNullOrEmpty(company.description)){
      this.ErrorMsg = "Description is blank";
      this.focusFrame(5, 0);
      return;
    }

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

}