// 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';
import * as ld from 'lodash';

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

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

	public categoriesSorted: AccountCategoryModel[];
	public accessRightsSorted: AccountAccessRightModel[];

	private readonly destroyRef = inject(DestroyRef);

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

		this.categoriesSorted = ld.orderBy(account.categories ?? [], ['name'], ['asc']);
		this.accessRightsSorted = ld.orderBy(account.accessRights!, ['isOwner', 'user.email'], ['desc', 'asc']);
	}

	/** Categories not yet assigned to this account (for the Add select). */
	get availableCategories(): AccountCategoryModel[] {
		const assigned = new Set((this.categoriesSorted ?? []).map(c => c.id));
		return (this.categories ?? []).filter(c => !assigned.has(c.id));
	}

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

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

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

	addCategory() {
		const categoryId = this.editForm.get('categoryId')?.value;
		if (!categoryId || !this.editForm.valid) {
			this.editForm.markAllAsTouched();
			return;
		}

		this.errorMessage = undefined;
		this.httpClient
			.put<AccountModel>(ApiRoutes.SettingsAccount.replace(':id', this.account.id!), this.editForm.value)
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe({
				next: account => {
					this.applyAccountCategories(account);
					this.editForm.patchValue({ categoryId: '' });
				},
				error: error => {
					this.errorMessage = error.detail;
				},
			});
	}

	removeCategory(category: AccountCategoryModel) {
		const url = ApiRoutes.SettingsAccountAccountCategory
			.replace(':id', this.account.id!)
			.replace(':categoryId', category.id!);

		this.errorMessage = undefined;
		this.httpClient
			.delete<AccountModel>(url)
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe({
				next: account => this.applyAccountCategories(account),
				error: error => {
					this.errorMessage = error.detail;
				},
			});
	}

	private applyAccountCategories(account: AccountModel) {
		this.account.categories = account.categories ?? [];
		this.categoriesSorted = ld.orderBy(this.account.categories, ['name'], ['asc']);
	}

	removeAccessRight(accessRight: AccountAccessRightModel) {

	}

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

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