// angular
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';

// libs
import Swal from 'sweetalert2';
import { MatDialog } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { SettingsItemEditComponent } from './edit.item.component';
import { ItemService } from '../../../services/item.service';
import { ISelectableModel } from '../../../core/models/selectable.model';
import { ItemModel } from '../../../model/item.model';
import { ItemCategoryModel } from '../../../model/item.category.model';

@Component({
	templateUrl: './item.component.html',
	styleUrls: ['./item.component.scss'],
})
export class SettingsItemComponent {
	public items?: ISelectableModel<ItemModel>[];
	public categories?: ItemCategoryModel[];
	public selectedCategory?: ItemCategoryModel;
	public selectedCount: number = 0;
	public category?: ItemCategoryModel;
	public categoryAddShow: boolean = false;
	public categoryAddName?: string;

	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private dialogModel: MatDialog,
		private httpClient: HttpClient,
		private itemService: ItemService,
	) {
	}

	ngOnInit(): void {
		this.load();
	}

	private load(categoryId?: string) {
		this.itemService.getCategories()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(data => {
				this.categories = data;
				var selected = data[0];
				if (categoryId) {
					var categories = this.categories.filter(x => x.id === categoryId);
					selected = categories.length === 0
						? selected
						: categories[0];
				}

				this.selectCategory(selected);
			});
	}

	public selectCategory(category: ItemCategoryModel) {
		this.selectedCategory = category;
		this.itemService.getItems(category.id)
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(data => {
				this.items = data.map<ISelectableModel<ItemModel>>(x => { return { model: x, selected: false } });
			});
	}

	public edit(item: ItemModel) {
		this.dialogModel.open(SettingsItemEditComponent, {
			width: '640px',
			disableClose: true,
			data: item,
		}).afterClosed()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(x => {
			if (x && x.refresh) {
				console.log(x.motion.categoryId);
				this.load(x.motion.categoryId);
			}
		});
	}

	public remove(category: ItemModel) {
		Swal.fire({
			title: 'Delete item from ' + category.name,
			showCancelButton: true,
			confirmButtonText: 'Delete',
			showLoaderOnConfirm: true,
			preConfirm: (name) => {
				return new Promise((resolve, reject) => {
					this.httpClient.delete(ApiRoutes.SettingsItemCategory.replace(':id', category.id!))
						.pipe(takeUntilDestroyed(this.destroyRef))
						.subscribe(data => {
							resolve(data);
						}, error => {
							Swal.showValidationMessage(error.detail);
							reject();
						});

				}).catch(x => {
					return false;
				});
			},
			allowOutsideClick: () => !Swal.isLoading(),
		}).then((result) => {
			this.load();
		});
	}

	onCheckboxChange(item: ISelectableModel<ItemModel>) {
		this.selectedCount += item.selected ? 1 : -1;
	}

	onCategoryChange(item: any) {
		var data = {
			category: item.value,
			items: this.items!.filter(x => x.selected).map(x => x.model.id)
		}
		this.httpClient.post(ApiRoutes.SettingsItems, data)
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(data => {
				this.category = undefined;
				this.selectedCount = 0;
				this.load();
			}, error => {
			});
	}
}
