// angular
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { Inject } from '@angular/core';
import { FormBuilder, FormGroup, 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';

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

	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private fb: FormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsItemCategoryEditComponent>,
		@Inject(MAT_DIALOG_DATA) public category: ItemCategoryModel
	) {
	}

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

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

	onSubmitClick() {
		if (this.editForm.valid) {
			this.errorMessage = undefined;
			if (!this.category.id) {
				this.httpClient
					.post<ItemCategoryModel>(ApiRoutes.SettingsItemCategories, this.editForm.value)
					.pipe(takeUntilDestroyed(this.destroyRef))
					.subscribe(response => {
						this.dialogRef.close({ category: response, refresh: true });
					}, error => {
						this.errorMessage = error.detail;
					});
			} else {
				this.httpClient
					.put<ItemCategoryModel>(ApiRoutes.SettingsItemCategory.replace(':id', this.category.id!), this.editForm.value)
					.pipe(takeUntilDestroyed(this.destroyRef))
					.subscribe(response => {
						this.dialogRef.close({ category: response, refresh: true });
					}, error => {
						this.errorMessage = error.detail;
					});
			}
		}
	}
}
