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

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

	settings: RestaurantSettings | undefined

	form = this._formBuilder.group({
		address: this._formBuilder.control('', Validators.required),
		email: this._formBuilder.control('', { validators: [Validators.required, Validators.email] }),
		phone: this._formBuilder.control<string | undefined>(undefined),
	})

	loading = false

	constructor() {
		this.loadSettings()
	}

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

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

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