// 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 } 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: './access.account.component.html',
	styleUrls: ['./access.account.component.scss'],
})
export class SettingsAccountAccessComponent {
	public editForm!: FormGroup;
	public errorMessage?: string;
	public currencies?: CurrencyModel[];
	public categories?: AccountCategoryModel[];
	public types = new Map<string, string>();

	public accessRightsSorted: AccountAccessRightModel[];

	private readonly destroyRef = inject(DestroyRef);

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

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

	}

	ngOnInit(): void {
		const accesses = this.fb.array(
			this.accessRightsSorted.map(x => this.fb.group({
				userId: [
					x.user.id
				],
				allowWrite: [{
					value: x.isAllowWrite,
					disabled: !x.isAllowDelete,
				}],
			}))
		);

		this.editForm = this.fb.group({
			email: [
				'',
			],
			allowWrite: [
				false,
			],
			accesses: accesses,
		});
	}

	removeAccessRight(accessRight: AccountAccessRightModel) {
		Swal.fire({
			title: 'Delete access ' + accessRight.user.email,
			showCancelButton: true,
			confirmButtonText: 'Delete',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					var url = ApiRoutes.SettingsAccountAccess
						.replace(':id', this.account.id!)
						.replace(':access', accessRight.user.id);

					this.errorMessage = undefined;
					this.httpClient
						.delete(url, this.editForm.value)
						.pipe(takeUntilDestroyed(this.destroyRef))
						.subscribe(response => {
							resolve(response);
						}, error => {
							Swal.showValidationMessage(error.detail);
							reject();
						});

				}).catch(x => {
					return false;
				});
			},
			allowOutsideClick: () => !Swal.isLoading(),
		}).then((result) => {
			if (result.isConfirmed) {
				this.dialogRef.close({ refresh: true });
			}
		});
	}

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

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