import { Component, Input, OnInit } from "@angular/core";
import { CommonModule } from "@angular/common";
import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap";
import {
  FormBuilder,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from "@angular/forms";
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 = "create";
  @Input() data: any = {};

  form: FormGroup = {} as FormGroup;

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

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

  initForm(): void {
    this.form = this.formBuilder.group({
      name: [null, [Validators.required, WhiteSpaceValidator.noWhiteSpace]],
      qty: [
        null,
        [Validators.required, Validators.pattern(/^[0-9]+(\.[0-9]{1,2})?$/)],
      ],
      unit: ["Kg", [Validators.required]],
    });

    // 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);
    }
  }
}
