import { DatePipe } from '@angular/common'
import { Component, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { SessionInfo } from '@core/types'
import { DefaultService, UserResponse } from '@api-client/angular'
import { ConfirmationModalComponent, ConfirmationModalConfig } from '@frontend/shared'
import { DialogService } from '@ngneat/dialog'
import { HotToastService } from '@ngxpert/hot-toast'
import { TranslocoDirective } from '@jsverse/transloco'
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'
import { finalize, of, switchMap } from 'rxjs'
import { AuthService } from '../../../auth'
import { I18nService } from '../../../core'
import { AddUserComponent } from './add-user/add-user.component'
import { SettingsStore } from '../../../+state'
import { LucideChevronLeft, LucideTrash } from '@lucide/angular'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-user-settings',
	templateUrl: './user-settings.component.html',
	imports: [TranslocoDirective, RouterLink, DatePipe, LucideTrash, LucideChevronLeft],
})
export class UserSettingsComponent {
	readonly _settingsStore = inject(SettingsStore)
	users: UserResponse[] = []
	currentUser: SessionInfo
	loading = false
	private readonly _toast = inject(HotToastService)
	private readonly _apiService = inject(DefaultService)
	private readonly _i18nService = inject(I18nService)
	private readonly _authService = inject(AuthService)
	private readonly _dialogService = inject(DialogService)

	constructor() {
		this.currentUser = this._authService.userData
		this.loadUsers()
	}

	addUser(): void {
		const dialogRef = this._dialogService.open(AddUserComponent)
		dialogRef.afterClosed$.pipe(untilDestroyed(this)).subscribe({
			next: () => this.loadUsers(),
		})
	}

	deleteUser(user: UserResponse): void {
		const dialogRef = this._dialogService.open(ConfirmationModalComponent, {
			data: {
				title: 'Delete User',
				message: 'Are you sure, you want to delete this user!',
				icon: { color: 'warn' },
			} as ConfirmationModalConfig,
		})
		dialogRef.afterClosed$
			.pipe(
				untilDestroyed(this),
				switchMap((confirmed) => {
					if (confirmed) {
						this.loading = true
						return this._apiService.userControllerDeleteById(user.id).pipe(finalize(() => (this.loading = false)))
					} else return of()
				}),
			)
			.subscribe({
				next: () => {
					this._toast.success(this._i18nService.translate('remove_user_success', { name: user.fullName }))
					this.loadUsers()
				},
				error: (error) => {
					this._toast.error(error.message)
				},
			})
	}

	private loadUsers(): void {
		this._apiService
			.userControllerFindAll()
			.pipe(untilDestroyed(this))
			.subscribe({
				next: (users) => (this.users = users),
			})
	}
}
