import { AsyncPipe, DatePipe } from '@angular/common'
import {
	ChangeDetectionStrategy,
	Component,
	ElementRef,
	inject,
	input,
	linkedSignal,
	output,
	viewChild,
} from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { FeatureKey } from '@core/types'
import { isFeatureEnabled } from '@core/utils'
import { ReservationSettings } from '@api-client/angular'
import { TranslocoDirective } from '@jsverse/transloco'
import { UntilDestroy } from '@ngneat/until-destroy'
import { map, Observable, timer } from 'rxjs'
import { SettingsStore } from '../../../+state'
import { AddReservationService } from '../../../shared'
import { NotificationsComponent } from '../notifications'
import { ReservationSearchComponent } from '../reservation-search'
import { FreeTableCounterComponent } from './free-table-counter.component'
import { LucideMenu, LucidePlus } from '@lucide/angular'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-header',
	templateUrl: './header.component.html',
	changeDetection: ChangeDetectionStrategy.OnPush,
	imports: [
		TranslocoDirective,
		ReservationSearchComponent,
		ReactiveFormsModule,
		FormsModule,
		FreeTableCounterComponent,
		NotificationsComponent,
		AsyncPipe,
		DatePipe,
		LucideMenu,
		LucidePlus,
	],
})
export class HeaderComponent {
	readonly origin = viewChild.required<ElementRef>('origin')
	readonly bgColorClass = input<string>()
	readonly toggleNavigation = output<string>()
	readonly _settingsStore = inject(SettingsStore)
	readonly autoApproveReservations = linkedSignal(
		() => this._settingsStore.settings()?.reservation.autoApproveReservations.enabled,
	)
	isFeatureEnabled = isFeatureEnabled
	FeatureKey = FeatureKey
	/** Observable that returns current time, emits a value every second */
	public readonly currentTime$: Observable<Date> = timer(0, 1000).pipe(map(() => new Date()))
	private readonly _addReservationService = inject(AddReservationService)

	addReservation(): void {
		this._addReservationService.add({ origin: this.origin() })
	}

	toggle(navigation: string) {
		this.toggleNavigation.emit(navigation)
	}

	async onAutoApproveReservationsChange() {
		const settings = this._settingsStore.settings()
		if (!settings) return

		const reservation: ReservationSettings = {
			...settings.reservation,
			autoApproveReservations: {
				...settings.reservation.autoApproveReservations,
				enabled: !this.autoApproveReservations(),
			},
		}

		await this._settingsStore.updateSettings({ reservation }, { showAutoApproveReservationEnabledToast: true })
	}
}
