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

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

	settings: KitchenSettings | undefined

	form = this._formBuilder.group({
		autoStartCooking: this._formBuilder.control(false, { validators: Validators.required }),
	})
	loading = false

	constructor() {
		this.loadSettings()
	}

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

		this.loading = true
		const kitchen = this.form.getRawValue()
		this._apiService
			.settingsControllerSave({ kitchen })
			.pipe(
				untilDestroyed(this),
				finalize(() => (this.loading = false)),
				this._toast.observe({
					success: this._i18nService.translate('kitchen_settings_update_success'),
				}),
			)
			.subscribe({
				next: () => {
					this.form.markAsPristine()
				},
			})
	}

	private loadSettings(): void {
		this._apiService
			.settingsControllerFind()
			.pipe(untilDestroyed(this))
			.subscribe(({ kitchen }) => {
				this.settings = kitchen
				if (kitchen) this.form.patchValue(kitchen)
			})
	}
}
