// angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Inject } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { UntypedFormGroup } from '@angular/forms';
import { Validators } from '@angular/forms';

// libs
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatDialogRef } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { ItemCategoryModel } from '../../../model/item.category.model';
import { ItemModel } from '../../../model/item.model';
import { ItemService } from '../../../services/item.service';

@Component({
	templateUrl: './edit.item.component.html',
	styleUrls: ['./edit.item.component.scss'],
})
export class SettingsItemEditComponent {
	public editForm!: UntypedFormGroup;
	public errorMessage?: string;
	public categories?: ItemCategoryModel[];

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsItemEditComponent>,
		private itemService: ItemService,
		@Inject(MAT_DIALOG_DATA) public item: ItemModel
	) {
	}

	ngOnInit(): void {
		this.editForm = this.fb.group({
			id: [
				this.item.id,
			],
			name: [
				this.item.name,
				[Validators.required],
			],
			category: [
				this.item.categoryId,
				[Validators.required],
			],
		});

		this.itemService
			.getCategories()
			.subscribe(x => this.categories = x);
	}

	closeDialog(): void {
		this.dialogRef.close();
	}

	onSubmitClick() {
		if (this.editForm.valid) {
			this.errorMessage = undefined;
			this.httpClient
				.put<ItemModel>(ApiRoutes.SettingsItem.replace(':id', this.item.id!), this.editForm.value)
				.subscribe(response => {
					this.dialogRef.close({ motion: response, refresh: true });
				}, error => {
					this.errorMessage = error.detail;
				});
		}
	}
}
