package com.gensee.multi_instance.ui.view

import android.util.Log
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.gensee.common.ServiceType
import com.gensee.multi_instance.ui.DemoInitParam
import com.gensee.multi_instance.ui.LiveType
import com.gensee.multi_instance.ui.viewmodel.InitParamsViewModel
import org.burnoutcrew.reorderable.ItemPosition
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.detectReorderAfterLongPress
import org.burnoutcrew.reorderable.rememberReorderableLazyGridState
import org.burnoutcrew.reorderable.reorderable
import java.lang.StringBuilder

/**
 *  author : guohaonan
 *  date : 2024/1/26 17:03
 *  description :
 */

//private var dataList:List<DemoInitParam> by mutableStateOf(mutableListOf<DemoInitParam>())

@Composable
fun DragLazyVerticalGrid(
    viewModel: InitParamsViewModel = viewModel(),
    innerPadding: PaddingValues,
    onItemClick: (Boolean, Int) -> Unit
) {
    var dataList:List<DemoInitParam> by remember {mutableStateOf(mutableListOf<DemoInitParam>())}

    dataList = viewModel.videoInfoList.toMutableList().apply {
        add(lastIndex + 1,BtnData())
    }
    Log.i("TAG", "DragLazyVerticalGrid: ")

    val state = rememberReorderableLazyGridState(onMove = { from: ItemPosition, to: ItemPosition ->
        if (from.index >= dataList.size || to.index >= dataList.size) {
            return@rememberReorderableLazyGridState
        }

        dataList = dataList.toMutableList().apply {
            add(to.index, removeAt(from.index))
        }

        viewModel.videoInfoList = viewModel.videoInfoList.toMutableList().apply {
            add(to.index, removeAt(from.index))
        }
    }, canDragOver = { _, _ ->
        true
    })

    LazyVerticalGrid(
        modifier = Modifier
            .padding(innerPadding)
            .fillMaxSize()
            .reorderable(state),
        state = state.gridState,
        verticalArrangement = Arrangement.spacedBy(20.dp),
        columns = GridCells.Fixed(3), // 设置每行显示的列数
        contentPadding = PaddingValues(10.dp) // 设置内容的内边距
    ) {
        items(dataList, { it.hashCode() }) { item ->
            if (item is BtnData) {
                Box() {
                    Card(
                        modifier = Modifier
                            .align(Alignment.Center)
                    ) {
                        AddItem(modifier = Modifier.clickable {
                            onItemClick(true, 0)
                        })
                    }
                }
            } else {
                ReorderableItem(state, item.hashCode()) { isDragging ->
                    val elevation = animateDpAsState(if (isDragging) 80.dp else 1.dp)
                    Card(
                        modifier = Modifier
                            .align(Alignment.Center)
                            .alpha(if (item.enable) 1.0f else 0.5f)
                            .detectReorderAfterLongPress(state),
                        elevation = CardDefaults.cardElevation(
                            defaultElevation = elevation.value
                        ),
                    ) {
                        Item(modifier = Modifier, item) {
                            onItemClick.invoke(false, dataList.indexOf(item))
                        }
                    }
                }
            }


        }
    }
}

@Composable
private fun Item(modifier: Modifier = Modifier, initParam: DemoInitParam, onClick: () -> Unit) {
//    val text = if (initParam.liveType == LiveType.LIVE) "直播" else "点播" + "/" + if (initParam.serviceType == ServiceType.WEBCAST) "WEBCAST" else "TRAINING"
    val txt = StringBuilder().append(if (initParam.liveType == LiveType.LIVE) "直播" else "点播")
        .append("/")
        .append(if (initParam.serviceType == ServiceType.WEBCAST) "W" else "T")
        .toString()
    Box(
        modifier = modifier
            .size(100.dp)
            .clickable {
                onClick()
            }
    ) {
        Text(
            text = initParam.number,
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.Center)
                .offset(y = (-10).dp)

        )
        Text(
            text = txt,
            fontSize = 15.sp,
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.Center)
                .offset(y = (20).dp)

        )
    }
}

@Composable
private fun AddItem(modifier: Modifier) {
    Box(
        modifier = modifier
            .size(100.dp)
    ) {
        Icon(
            Icons.Default.Add,
            contentDescription = "Example Icon",
            modifier = Modifier
                .align(Alignment.Center)
                .offset(y = -10.dp)
        )
        Text(
            text = "添加",
            color = Color.Black,
            modifier = Modifier
                .align(Alignment.Center)
                .offset(y = 20.dp)
        )
    }
}

private class BtnData : DemoInitParam() {
    override fun getNumber(): String {
        return "super.getNumber()"
    }
}