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

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

  form: FormGroup = {} as FormGroup;

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

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

  initForm(): void {
    this.form = this.formBuilder.group({
      old_password: [
        null,
        [Validators.required, WhiteSpaceValidator.noWhiteSpace],
      ],
      new_password: [
        null,
        [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);
    }
  }

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