// 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 Swal from 'sweetalert2';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { AccountModel } from '../../../model/account.model';
import { MatDialogRef } from '@angular/material/dialog';
import { CurrencyService } from '../../../services/currency.service';
import { CurrencyModel } from '../../../model/currency.model';
import { AccountCategoryService } from '../../../services/account.category.service';
import { AccountCategoryModel } from '../../../model/account.category.model';
import { AuthService } from '../../../core/service/auth.service';

@Component({
	templateUrl: './add.account.component.html',
	styleUrls: ['./add.account.component.scss'],
})
export class SettingsAccountAddComponent {
	public editForm!: UntypedFormGroup;
	public errorMessage?: string;
	public currencies?: CurrencyModel[];
	public categories?: AccountCategoryModel[];
	public username: string;

	constructor(
		private fb: UntypedFormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsAccountAddComponent>,
		private currencyService: CurrencyService,
		private accountCategoryService: AccountCategoryService,
		private authService: AuthService,
		@Inject(MAT_DIALOG_DATA) public account: AccountModel
	) {
		this.username = authService.currentUserValue.userName;
	}

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

		this.currencyService
			.getCurrencies()
			.subscribe(x => this.currencies = x);

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

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

	onSubmitClick() {
		if (this.editForm.valid) {
			this.errorMessage = undefined;
			this.httpClient
				.post<AccountModel>(ApiRoutes.SettingsAccounts, this.editForm.value)
				.subscribe(response => {
					this.dialogRef.close({ refresh: true });
				}, error => {
					this.errorMessage = error.detail;
				});
		}
	}
}
