import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ITodoModel } from '@fleio-api/plugins/todo/model/todo.model';
import { TodoApiService } from '@fleio-api/plugins/todo/todo-api.service';
import { ITodoCreateOptionsModel } from '@fleio-api/plugins/todo/model/todo-create-options.model';

@Component({
  selector: 'app-todo-edit-form',
  templateUrl: './todo-edit-form.component.html',
  styleUrls: ['./todo-edit-form.component.scss']
})
export class TodoEditFormComponent extends DetailsFormBase<ITodoModel> implements OnInit {
  todoForm = this.formBuilder.group({
    title: ['', Validators.required],
    status: ['open', Validators.required],
    assigned_to: [null],
    description: [''],
  });
  assignedToSelectedPlaceholder = $localize`Assigned to`;
  assignedToUnselectedPlaceholder = $localize`Select assignee`;

  createOptions: ITodoCreateOptionsModel;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private todoApiService: TodoApiService,
    private router: Router,
    private config: ConfigService,
    private activatedRoute: ActivatedRoute,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = (action: IAction) => this.todoActions(action);
    }
    this.createOptions = this.activatedRoute.snapshot.data.createOptions;

    if (this.object?.id) {
      this.todoForm.patchValue(this.object);
      this.todoForm.controls.assigned_to.setValue({
        id: this.object.assigned_to,
        full_name: this.object.assigned_to_display,
      });
    }
  }

  todoActions(action: IAction): Observable<IActionResult> {
    const value = this.todoForm.value as ITodoModel;
    if (value.assigned_to instanceof Object) {
      if (value.assigned_to.id) {
        value.assigned_to = value.assigned_to.id;
      } else {
        value.assigned_to = null;
      }
    }
    this.createOrUpdate(
      this.todoApiService,
      value,
    ).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('todo')
      ).catch(() => {
      });
    });

    return of(null);
  }
}
