import { Component, inject } from '@angular/core'
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'
import { RouterLink } from '@angular/router'
import { DefaultService, UserResponse } from '@api-client/angular'
import { LoadingButtonDirective } from '@frontend/shared'
import { TranslocoDirective } from '@jsverse/transloco'
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'
import { finalize } from 'rxjs'
import { AuthService } from '../../../auth'
import { I18nService } from '../../../core'
import { LucideChevronLeft } from '@lucide/angular'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-langauge-settings',
	templateUrl: './langauge-settings.component.html',
	imports: [TranslocoDirective, RouterLink, ReactiveFormsModule, LoadingButtonDirective, LucideChevronLeft],
})
export class LangaugeSettingsComponent {
	private readonly _apiService = inject(DefaultService)
	private readonly _authService = inject(AuthService)
	private readonly _formBuilder = inject(NonNullableFormBuilder)
	private readonly _i18nService = inject(I18nService)

	user: UserResponse | undefined
	loading = false

	availableLanguages: Language[] = [
		{
			title: 'English',
			langId: 'en',
			icon: '/assets/icons/flags/uk_round.png',
		},
		{
			title: 'Deutsch',
			langId: 'de',
			icon: '/assets/icons/flags/germany_round.png',
		},
	]
	form = this._formBuilder.group({
		preferedLanguage: this._formBuilder.control('en', Validators.required),
	})

	constructor() {
		this.loadUser(this._authService.userData.id)
	}

	save(): void {
		if (this.form.invalid) return

		this.loading = true
		const langauge = this.form.getRawValue().preferedLanguage
		this._apiService
			.userControllerUpdateById(this.user!.id, { id: this.user!.id, preferedLanguage: langauge })
			.pipe(
				untilDestroyed(this),
				finalize(() => (this.loading = false)),
			)
			.subscribe({
				next: () => {
					this._i18nService.setLanguage(langauge)
					location.reload()
				},
			})
	}

	private loadUser(id: string): void {
		this._apiService
			.userControllerFindById(id)
			.pipe(untilDestroyed(this))
			.subscribe({
				next: (user) => {
					this.user = user
					this.form.patchValue({ preferedLanguage: user.preferedLanguage ?? 'en' })
				},
			})
	}
}

interface Language {
	title: string
	langId: string
	icon: string
}
