// 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 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';
import { AccountService } from '../../../services/account.service';

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

	private readonly destroyRef = inject(DestroyRef);

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

	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],
			],
			type: [
				this.account.type
			]
		});

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

		this.accountCategoryService
			.getCategories()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.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)
				.pipe(takeUntilDestroyed(this.destroyRef))
				.subscribe(response => {
					this.dialogRef.close({ refresh: true });
				}, error => {
					this.errorMessage = error.detail;
				});
		}
	}
}
