import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { ComponentBase } from '@core/base/common-base';
import { from, take, takeUntil } from 'rxjs';
import { BaseForm } from '@core/base/base-form';
import { AuthService } from '@core/services/authentication/auth.service';
import { ToastrService } from 'ngx-toastr';
import { SharedService } from '../../../core/services/shared.service';

import {
  FormGroup,
  UntypedFormControl,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import {
  JOB_TITLE,
  QUALIFICATION,
  UNIVERISTY,
  COUNTRY,
  INDUSTRY,
  CITY,
} from '@core/models/authenticcation.model';

@Component({
  selector: 'app-signup-employee',
  templateUrl: './signup-employee.component.html',
  styleUrls: ['./signup-employee.component.scss'],
})
export class SignupEmployeeComponent
  extends ComponentBase
  implements OnInit, BaseForm
{
  form!: FormGroup;
  multiPartForm = new FormData();
  jobTitles: JOB_TITLE[] = [];
  qualificationList: QUALIFICATION[] = [];
  univerisites: UNIVERISTY[] = [];
  countries: COUNTRY[] = [];
  cities: CITY[] = [];
  industriesList: INDUSTRY[] = [];

  constructor(
    private readonly route: ActivatedRoute,
    private readonly authService: AuthService,
    private readonly toastr: ToastrService,
    private readonly sharedService: SharedService,
    private readonly router: Router
  ) {
    super();
  }

  ngOnInit(): void {
    this.initForm();
    this.getJobTitles();
    this.getQualifications();
    this.getUniversities();
    this.getContries();
    this.getIndustries();
    this.route.queryParams
      .pipe(takeUntil(this.destroy$))
      .subscribe((params: Params) => {
        this.form.patchValue({
          userType: +params['type'],
        });
      });
  }

  initForm(): void {
    this.form = new UntypedFormGroup({
      firstName: new UntypedFormControl(null, [Validators.required]),
      lastName: new UntypedFormControl(null, [Validators.required]),
      dateOfBirth: new UntypedFormControl(null, [Validators.required]),
      email: new UntypedFormControl(null, [
        Validators.required,
        Validators.email,
      ]),
      idNumber: new UntypedFormControl(null, [Validators.required]),
      phoneNumber: new UntypedFormControl(null, [Validators.required]),
      userType: new UntypedFormControl(null, [Validators.required]),
      linkedInLink: new UntypedFormControl(null, [Validators.required]),
      userName: new UntypedFormControl(null, [
        Validators.required,
        Validators.minLength(6),
      ]),
      password: new UntypedFormControl(null, [
        Validators.required,
        Validators.pattern(this.sharedService.StrongPasswordRegx),
        Validators.minLength(8),
      ]),
      favoriteName: new UntypedFormControl(null, [Validators.required]),
      passportNumber: new UntypedFormControl(null, [Validators.required]),
      qualificationId: new UntypedFormControl(null, [Validators.required]),
      universityId: new UntypedFormControl(null, [Validators.required]),
      jobTitleId: new UntypedFormControl(null, [Validators.required]),
      industryId: new UntypedFormControl(null, [Validators.required]),
      taxNumber: new UntypedFormControl(null, [Validators.required]),
      incomeTaxValue: new UntypedFormControl(null, Validators.required),
      cvAttach: new UntypedFormControl(null),
      passportAttach: new UntypedFormControl(null),
      eduCertificateAttach: new UntypedFormControl(null),
      experienceCertificateAttach: new UntypedFormControl(null),
      profCertificateAttach: new UntypedFormControl(null),
      userAddress: new UntypedFormGroup({
        countryId: new UntypedFormControl(null, [Validators.required]),
        cityId: new UntypedFormControl(null, [Validators.required]),
        postalCode: new UntypedFormControl(null, [Validators.required]),
        addressDesc: new UntypedFormControl(null, [Validators.required]),
      }),
    });
  }

  getJobTitles(): void {
    this.authService
      .getJobtitles()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.jobTitles = res;
      });
  }

  getQualifications(): void {
    this.authService
      .getQualifications()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.qualificationList = res;
      });
  }

  getUniversities(): void {
    this.authService
      .getUniversity()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.univerisites = res;
      });
  }

  getIndustries(): void {
    this.authService
      .getIndustries()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.industriesList = res;
      });
  }

  getContries(): void {
    this.authService
      .getCountries()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.countries = res;
      });
  }

  onChangeCountry(event: any): void {
    this.authService
      .getCities({ CountryId: event.target.value })
      .subscribe((res) => {
        this.cities = res;
      });
  }

  onUploadFile(event: any): void {
    if (event.file) {
      this.form.patchValue({ [event.type]: event.file });
    } else {
      this.form.patchValue({ [event.type]: null });
    }
  }

  onSubmit(): void {
    const multiPartForm = new FormData();
    if (this.submitValidity(this.form)) {
      this.loading = true;
      for (const key in { ...this.form.value }) {
        if (this.form.value.hasOwnProperty(key)) {
          if (this.form.get(key)?.value) {
            multiPartForm.append(key, this.form.get(key)?.value);
          }
        }
      }

      this.authService
        .addEmployee(multiPartForm)
        .pipe(takeUntil(this.destroy$))
        .subscribe(
          (res) => {
            this.toastr.success('Registeration Successfully !');
            this.router.navigate(['/auth']);
            this.loading = false;
          },
          (error) => {
            this.loading = false;
          }
        );
    }
  }
}
