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

@Component({
  selector: "app-action-faq",
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, CKEditorModule],
  templateUrl: "./action.component.html",
  styleUrls: ["./action.component.scss"],
})
export class ActionFaq implements OnInit {
  public Editor = ClassicEditor;
  @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({
      title: [null, [Validators.required, WhiteSpaceValidator.noWhiteSpace]],
      desc: [null, [Validators.required, WhiteSpaceValidator.noWhiteSpace]],
      order: [
        null,
        [
          Validators.required,
          Validators.pattern(/^[0-9]+(\.[0-9]{1,2})?$/),
          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);
    }
  }
}
