import { AsyncPipe } from '@angular/common'
import { Component, inject } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { Router, RouterLink } from '@angular/router'
import { TableCombinationResponse, TableResponse, UserResponse } from '@api-client/angular'
import { LoadingButtonDirective } from '@frontend/shared'
import { NgSelectComponent } from '@ng-select/ng-select'
import { TranslocoDirective } from '@jsverse/transloco'
import { Observable, combineLatest, map, tap } from 'rxjs'
import { RoomPlanSettingsStore, SettingsView } from '../room-plan.store'
import { LucideTrash, LucideUser, LucideX } from '@lucide/angular'

@Component({
	selector: 'kadi-room-details-settings',
	templateUrl: './room-details-settings.component.html',
	styles: [
		`
			.w-selection {
				@media (min-width: 1280px) {
					width: 28rem;
					min-width: 28rem;
					max-width: 28rem;
				}
			}
		`,
	],
	imports: [
		TranslocoDirective,
		RouterLink,
		ReactiveFormsModule,
		FormsModule,
		NgSelectComponent,
		LoadingButtonDirective,
		AsyncPipe,
		LucideX,
		LucideTrash,
		LucideUser,
	],
})
export class RoomDetailsSettingsComponent {
	private readonly _router = inject(Router)
	private readonly _store = inject(RoomPlanSettingsStore)

	SettingsView = SettingsView

	vm$: Observable<{
		combinations: TableCombinationResponse[]
		selectedTable?: TableResponse
		selectedTableIndex: number
		selectedCombinationIndex?: number
		users: UserResponse[]
		loading: boolean
		isScreenSmall: boolean
		activeView: SettingsView
	}>

	constructor() {
		this.vm$ = combineLatest([
			this._store.combinations$,
			this._store.selectedTable$,
			this._store.selectedTableIndex$,
			this._store.users$,
			this._store.loading$,
			this._store.isScreenSmall$,
			this._store.activeView$,
		]).pipe(
			map(([combinations, selectedTable, selectedTableIndex, users, loading, isScreenSmall, activeView]) => ({
				combinations,
				selectedTable,
				selectedTableIndex: selectedTableIndex as number,
				users,
				loading,
				isScreenSmall,
				activeView,
			})),
			tap((data) => {
				if (!data.selectedTable && data.isScreenSmall) this._router.navigateByUrl('/settings/room-plan')
			}),
		)
	}

	addTable(): void {
		this._store.addTable()
	}

	removeTable(index: number): void {
		this._store.removeTable(index)
	}

	increaseCapacity(index: number): void {
		this._store.increaseCapacity(index)
	}

	decreaseCapacity(index: number): void {
		this._store.decreaseCapacity(index)
	}

	save(): void {
		this._store.saveTables()
	}

	changeView(view: SettingsView): void {
		this._store.changeView(view)
	}

	addCombination(): void {
		this._store.addCombination()
	}

	removeCombination(index: number): void {
		this._store.removeCombination(index)
	}

	selectCombination(index: number): void {
		this._store.selectCombination(index)
	}

	protected readonly close = close
}
