// import { CatalogRolesComponent } from '@/shared/catalog/roles';
import { MustMatch, usernameValidator } from '@/core/validators';
import { AbstractForm } from '@/shared/abstractClasses';
import {
  DeviceIdComponent,
  NameComponent,
  PosTypeComponent,
  ProviderIdComponent,
  SerialNumberComponent,
  SharedPasswordInputComponent,
  UsernameComponent,
} from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { fieldControl } from '@/shared/constants/fields';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { IPosRequest, IPosResponse } from '../../models';
import { PartnerPosesService } from '../../services/poses.service';

@Component({
  selector: 'partner-consumer-pos-form-content',
  templateUrl: './form.component.html',
  imports: [
    ReactiveFormsModule,
    NameComponent,
    FormFooterActionsComponent,
    DeviceIdComponent,
    ProviderIdComponent,
    PosTypeComponent,
    SerialNumberComponent,
    UsernameComponent,
    Divider,
    SharedPasswordInputComponent,
  ],
})
export class ConsumerPosFormContentComponent extends AbstractForm<IPosRequest, IPosResponse> {
  private readonly service = inject(PartnerPosesService);

  @Input({ required: true }) consumerId!: string;
  @Input({ required: true }) businessActivityId!: string;
  @Input({ required: true }) complexId!: string;
  @Input() posId!: string;

  initForm = () => {
    const form = this.fb.group({
      name: fieldControl.name(this.initialValues?.name || ''),
      pos_type: fieldControl.pos_type(this.initialValues?.pos_type || ''),
      serial_number: fieldControl.serial_number(this.initialValues?.serial_number || ''),
      device_id: fieldControl.device_id(this.initialValues?.device?.id || ''),
      provider_id: fieldControl.provider_id(this.initialValues?.provider?.id || ''),
      username: fieldControl.username(),
      password: fieldControl.password(),
      confirmPassword: fieldControl.confirmPassword(),
    });

    form.controls.pos_type.valueChanges.subscribe((value) => {
      if (value === 'PSP') {
        form.controls.serial_number.setValidators([Validators.required]);
        form.controls.device_id.setValidators([Validators.required]);
        form.controls.provider_id.setValidators([Validators.required]);
        form.controls.serial_number.enable({ emitEvent: false });
        form.controls.device_id.enable({ emitEvent: false });
        form.controls.provider_id.enable({ emitEvent: false });
      } else {
        form.controls.serial_number.clearValidators();
        form.controls.device_id.clearValidators();
        form.controls.provider_id.clearValidators();
        form.controls.serial_number.reset('');
        form.controls.device_id.reset('');
        form.controls.provider_id.reset('');
        form.controls.serial_number.disable({ emitEvent: false });
        form.controls.device_id.disable({ emitEvent: false });
        form.controls.provider_id.disable({ emitEvent: false });
      }

      form.controls.serial_number.updateValueAndValidity({ emitEvent: false });
      form.controls.device_id.updateValueAndValidity({ emitEvent: false });
      form.controls.provider_id.updateValueAndValidity({ emitEvent: false });
    });
    form.controls.pos_type.updateValueAndValidity({ emitEvent: true });

    if (this.editMode) {
      // @ts-ignore
      form.removeControl('username');
      // @ts-ignore
      form.removeControl('password');
      // @ts-ignore
      form.removeControl('confirmPassword');
      form.removeValidators([MustMatch('password', 'confirmPassword')]);
    } else {
      form.controls.username.setValidators([Validators.required, usernameValidator()]);
      form.controls.username.updateValueAndValidity({ emitEvent: false });
      form.addValidators([MustMatch('password', 'confirmPassword')]);
    }

    return form;
  };

  form = this.initForm();

  get preparedTitle() {
    return `${this.editMode ? 'ویرایش' : 'افزودن'} پایانه فروش`;
  }

  override ngOnChanges(): void {
    this.form = this.initForm();
  }

  submitForm() {
    const formValue = this.form.value as IPosRequest & { confirmPassword?: string };
    if (this.editMode) {
      return this.service.update(this.businessActivityId, this.complexId, this.posId, formValue);
    }
    const { confirmPassword, ...rest } = formValue;
    return this.service.create(this.businessActivityId, this.complexId, rest);
  }
}
