import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { User } from 'src/app/models/user';
import { TaskService } from 'src/app/services/task.service';
import { UserService } from 'src/app/services/user.service';

@Component({
  selector: 'app-edit-task',
  templateUrl: './edit-task.page.html',
  styleUrls: ['./edit-task.page.scss'],
  standalone: false,
})
export class EditTaskPage implements OnInit {
  form: FormGroup;
  id: number;
  isAddMode: boolean;
  users: Array<User> = [{id: 0, name: 'unassigned'}];

  constructor(
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private taskService: TaskService,
    private userService: UserService,
    private router: Router,
    private location: Location
  ) {
    this.id = this.route.snapshot.params['id'];
    this.isAddMode = !this.id;

    this.form = this.formBuilder.group({
      name: ['', Validators.required],
      reward: ['', Validators.required],
      assigned: [0, Validators.required]
    });
  }

  ngOnInit() {
    this.userService.getUserList().subscribe(users => {
      this.users.push(...users);
    });

    if (!this.isAddMode) {
      this.taskService.getTaskById(this.id).subscribe(task => {
        this.form.setValue({
          name: task.name,
          reward: task.reward,
          assigned: task.assigned !== null ? task.assigned : 0
        });
      });
    }
  }

  submit() {
    const formValue = this.form.value;
    let assigned: number | null = Number(formValue.assigned);
    if (assigned === 0) {
      assigned = null;
    };

    const task = {
      name: formValue.name,
      reward: formValue.reward,
      assigned
    };

    if (this.isAddMode) {
      this.taskService.createTask(task);
    } else {
      this.taskService.updateTask(this.id, task);
    }

    this.router.navigate(['/tabs/tasks']);
  }

  deleteTask() {
    this.taskService.deleteTask(this.id);
    this.router.navigate(['/tabs/tasks']);
  }

  completeAndRecreateTask() {
    const formValue = this.form.value;
    let assigned: number | null = Number(formValue.assigned);
    if (assigned === 0) {
      assigned = null;
    };

    const task = {
      name: formValue.name,
      reward: formValue.reward,
      assigned
    };

    this.taskService.createTask(task);
    this.taskService.completeTask(this.id);

    this.router.navigate(['/tabs/tasks']);
  }

  navigateBack() {
    this.location.back();
  }
}
