import { MustMatch } from '@/core/validators';
import { AbstractForm } from '@/shared/abstractClasses';
import {
  FirstNameComponent,
  LastNameComponent,
  LegalNameComponent,
  MobileNumberComponent,
  NationalCodeComponent,
  RegistrationCodeComponent,
  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, signal } from '@angular/core';
import { FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { SelectButton } from 'primeng/selectbutton';
import { IPartnerConsumerRequest, IPartnerConsumerResponse } from '../models';
import { ConsumersService } from '../services/main.service';

@Component({
  selector: 'partner-consumer-form-content',
  templateUrl: './form.component.html',
  imports: [
    FormsModule,
    ReactiveFormsModule,
    FirstNameComponent,
    LastNameComponent,
    MobileNumberComponent,
    NationalCodeComponent,
    LegalNameComponent,
    RegistrationCodeComponent,
    UsernameComponent,
    FormFooterActionsComponent,
    Divider,
    SharedPasswordInputComponent,
    SelectButton,
  ],
})
export class ConsumerUserFormContentComponent extends AbstractForm<
  IPartnerConsumerRequest,
  IPartnerConsumerResponse
> {
  @Input() consumerId?: string;
  private service = inject(ConsumersService);

  consumerTypes = [
    {
      value: 'INDIVIDUAL',
      name: 'حقیقی',
    },
    {
      value: 'LEGAL',
      name: 'حقوقی',
    },
  ];

  selectedType = signal<string>(this.initialValues?.type?.value || this.consumerTypes[0].value);

  initForm = () => {
    this.selectedType.set(this.initialValues?.type?.value || this.consumerTypes[0].value);
    const legal = this.fb.group({
      name: fieldControl.legal_name(this.initialValues?.legal?.name || ''),
      registration_code: fieldControl.registration_code(
        this.initialValues?.legal?.registration_code || '',
      ),
    });
    const individual = this.fb.group({
      first_name: fieldControl.first_name(this.initialValues?.individual?.first_name || ''),
      last_name: fieldControl.last_name(this.initialValues?.individual?.last_name || ''),
      mobile_number: fieldControl.mobile_number(
        this.initialValues?.individual?.mobile_number || '',
      ),
      national_code: fieldControl.national_code(
        this.initialValues?.individual?.national_code || '',
      ),
    });
    const form = this.fb.group({
      type: [this.initialValues?.type || this.consumerTypes[0].value, [Validators.required]],
      legal,
      individual,
      username: [''],
      password: [''],
      confirmPassword: [''],
    });

    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.addControl(
        'username',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: fieldControl.username('')[1],
        }),
      );
      form.addControl(
        'password',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: [Validators.required],
        }),
      );
      form.addControl(
        'confirmPassword',
        this.fb.control<string>('', {
          nonNullable: true,
          validators: [Validators.required],
        }),
      );

      form.addValidators([MustMatch('password', 'confirmPassword')]);
    }

    if (form.controls.type.value === 'LEGAL') {
      // @ts-ignore
      form.addControl('legal', legal);
      // @ts-ignore
      form.removeControl('individual');
    } else {
      // @ts-ignore
      form.addControl('individual', individual);
      // @ts-ignore
      form.removeControl('legal');
    }

    form.controls.type.valueChanges.subscribe((type) => {
      if (type === 'LEGAL') {
        // @ts-ignore
        form.addControl('legal', legal);
        // @ts-ignore
        form.removeControl('individual');
      } else {
        // @ts-ignore
        form.addControl('individual', individual);
        // @ts-ignore
        form.removeControl('legal');
      }
    });

    return form;
  };

  form = this.initForm();

  override ngOnChanges() {
    this.form.patchValue((this.initialValues as any) || {});
    if (this.editMode && !this.consumerId) {
      throw 'missing some arguments';
    }

    this.form = this.initForm();
  }

  override submitForm(payload: IPartnerConsumerRequest) {
    if (this.editMode) {
      return this.service.update(this.consumerId!, payload);
    }
    // @ts-ignore
    const { confirmPassword, ...rest } = payload;
    return this.service.create(rest);
  }

  changeType(newType: string) {
    this.form.controls.type.setValue(newType);
  }
}
