package com.pixelized.biblib.ui.screen.home.sort

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.pixelized.biblib.R
import com.pixelized.biblib.model.search.SortType
import com.pixelized.biblib.model.search.SortValue
import dagger.hilt.android.lifecycle.HiltViewModel
import org.burnoutcrew.reorderable.ItemPosition
import javax.inject.Inject

@HiltViewModel
class BookSortViewModel @Inject constructor() : ViewModel() {
    val items = mutableStateOf(
        listOf(
            SortUio(
                id = SortType.New,
                label = R.string.search_sort_new,
                ascending = true,
            ),
            SortUio(
                id = SortType.Title,
                label = R.string.search_sort_title,
                ascending = null,
            ),
            SortUio(
                id = SortType.Series,
                label = R.string.search_sort_series,
                ascending = null,
            ),
        )
    )

    fun update(sortBy: Map<SortType, SortValue?>) {
        items.value = items.value.map { item ->
            item.copy(ascending = sortBy[item.id]?.let { it == SortValue.ASC })
        }
    }

    fun onSort(item: SortUio) {
        val index = items.value.indexOf(item)
        items.value = items.value.toMutableList().also {
            it[index] = item.copy(
                ascending = when (item.ascending) {
                    true -> false
                    false -> null
                    null -> true
                }
            )
        }
    }

    fun onMove(from: ItemPosition, to: ItemPosition) {
        items.value = items.value.toMutableList().apply {
            add(to.index, removeAt(from.index))
        }
    }

    fun onConfirm(): Map<SortType, SortValue?> {
        val data: List<Pair<SortType, SortValue?>> = items.value.map { item ->
            item.id to item.ascending?.let { if (it) SortValue.ASC else SortValue.DESC }
        }
        return mapOf(*data.toTypedArray())
    }
}