import { CommonModule } from "@angular/common";
import { Component, OnInit, Input } from "@angular/core";
import {
  FormBuilder,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from "@angular/forms";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap";
import { WhiteSpaceValidator } from "src/app/cores/form-validators/whitespace";
import { EmailValidator } from "src/app/cores/form-validators/email-validation";

@Component({
  selector: "app-action",
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: "./action.component.html",
  styleUrls: ["./action.component.scss"],
})
export class ActionSurveyor implements OnInit {
  @Input() action = "create";
  @Input() data: any = {};

  form: FormGroup = {} as FormGroup;

  constructor(
    public activeModal: NgbActiveModal,
    public helpers: HelpersService,
    private formBuilder: FormBuilder
  ) {}

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.form = this.formBuilder.group({
      urole_id: ["1b4701ab-da41-405b-9fe3-039a4daf0094"],
      fullname: [null, [Validators.required, WhiteSpaceValidator.noWhiteSpace]],
      shortname: [
        null,
        [Validators.required, WhiteSpaceValidator.noWhiteSpace],
      ],
      username: [null, [Validators.required, WhiteSpaceValidator.noWhiteSpace]],
      email: [
        null,
        [
          Validators.required,
          WhiteSpaceValidator.noWhiteSpace,
          EmailValidator.emailValidation,
        ],
      ],
      pwd: [
        "pengelola456",
        [Validators.required, WhiteSpaceValidator.noWhiteSpace],
      ],
    });

    // set form if action is update and there is data
    if (this.action === "update" && this.data) {
      this.form.patchValue(this.data);
    }
  }

  onResetPassword(): void {
    this.action === "update" && this.data;
    this.form = this.formBuilder.group({
      pwd: ["password123"],
    });
    this.activeModal.close(this.form.value);
  }

  onSubmit(): void {
    if (this.form.valid) {
      this.activeModal.close(this.form.value);
    }
  }
}
