import { Component, inject } from '@angular/core'
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'
import { DashboardStore } from '../../dashboard.store'
import { Observable, combineLatest, map, startWith, take } from 'rxjs'
import { MenuItem } from '../../types'
import { FormControl, ReactiveFormsModule } from '@angular/forms'
import { AsyncPipe, CurrencyPipe } from '@angular/common'
import { LucideMinus, LucidePlus, LucideSearch } from '@lucide/angular'

@UntilDestroy({ checkProperties: true })
@Component({
	selector: 'kadi-order-menu-view',
	templateUrl: './menu.component.html',
	imports: [ReactiveFormsModule, AsyncPipe, CurrencyPipe, LucidePlus, LucideMinus, LucideSearch],
})
export class OrderMenuViewComponent {
	private readonly _store = inject(DashboardStore)

	readonly items$: Observable<MenuItem[]>
	filterdItems$: Observable<MenuItem[]>

	searchControl = new FormControl('')

	constructor() {
		this.items$ = this._store.select(({ menuItems }) => menuItems)

		this.filterdItems$ = combineLatest([this.items$, this.searchControl.valueChanges.pipe(startWith(''))]).pipe(
			map(([items, searchTerm]) => {
				if (!searchTerm || searchTerm.length === 0) return items
				return items.filter((item) => item.name.toLowerCase().includes(searchTerm.toLowerCase()))
			}),
		)
	}

	increment(itemId: string): void {
		this.items$.pipe(take(1), untilDestroyed(this)).subscribe({
			next: (items) => {
				const index = items.findIndex((item) => item.id === itemId)
				items[index].cartQuantity += 1

				this._store.patchState({ menuItems: items })
			},
		})
	}

	decrement(itemId: string): void {
		this.items$.pipe(take(1), untilDestroyed(this)).subscribe({
			next: (items) => {
				const index = items.findIndex((item) => item.id === itemId)

				if (items[index].cartQuantity === 0) return

				items[index].cartQuantity -= 1

				this._store.patchState({ menuItems: items })
			},
		})
	}
}
