import { Component, OnInit } from '@angular/core';
import { BaseForm } from '@core/base/base-form';
import { ComponentBase } from '@core/base/common-base';

import {
  FormGroup,
  UntypedFormControl,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { COUNTRY } from '@core/models/authenticcation.model';
import { AuthService } from '@core/services/authentication/auth.service';
import { takeUntil } from 'rxjs';
import { CITY } from '../../../core/models/authenticcation.model';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';

@Component({
  selector: 'app-signup-business',
  templateUrl: './signup-business.component.html',
  styleUrls: ['./signup-business.component.scss'],
})
export class SignupBusinessComponent
  extends ComponentBase
  implements OnInit, BaseForm
{
  form!: FormGroup;
  countries: COUNTRY[] = [];
  cities: CITY[] = [];

  constructor(
    private readonly authService: AuthService,
    private readonly router: Router,
    private readonly toastr: ToastrService
  ) {
    super();
  }
  ngOnInit(): void {
    this.initForm();
    this.getCountries();
  }

  initForm(): void {
    this.form = new UntypedFormGroup({
      companyName: new UntypedFormControl(null, [Validators.required]),
      crNumber: new UntypedFormControl(null, [Validators.required]),
      taxNumber: new UntypedFormControl(null, [Validators.required]),
      // commercialRegAttach: new UntypedFormControl(null),
      // taxDeclarationAttach: new UntypedFormControl(null),
      // passportAttach: new UntypedFormControl(null),
      // experienceCertificateAttach: new UntypedFormControl(null),
      // idAttach: new UntypedFormControl(null),

      userAddress: new UntypedFormGroup({
        countryId: new UntypedFormControl(null, [Validators.required]),
        city: new UntypedFormControl(null, [Validators.required]),
        postalCode: new UntypedFormControl(null, [Validators.required]),
        addressDesc: new UntypedFormControl(null, [Validators.required]),
      }),

      companyUser: new UntypedFormGroup({
        firstName: new UntypedFormControl(null, [Validators.required]),
        lastName: new UntypedFormControl(null, [Validators.required]),
        idNumber: new UntypedFormControl(null, [Validators.required]),
        passportNumber: new UntypedFormControl(null, [Validators.required]),
        phoneNumber: new UntypedFormControl(null, [Validators.required]),
        email: new UntypedFormControl(null, [Validators.required]),
      }),
    });
  }

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

  onChangeCountry(event: any): void {
    const id = event.target.value;
    this.getCities(id);
  }

  getCities(id: number): void {
    this.authService
      .getCities({ CountryId: id })
      .pipe(takeUntil(this.destroy$))
      .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();

    const formData = {
      ...this.form.value,
      CompanyUser: JSON.stringify({
        ...this.form.get('companyUser')?.value,
        userAddress: this.form.get('userAddress')?.value,
      }),
    };

    delete formData.userAddress;
    delete formData.companyUser;

    console.log(formData);
    if (super.submitValidity(this.form)) {
      for (const key in { ...formData }) {
        if (formData.hasOwnProperty(key)) {
          if (formData[key]) {
            multiPartForm.append(key, formData[key]);
          }
        }
      }

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