package com.aiosman.riderpro

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.drawBehind
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Preview
@Composable
fun EditModification() {
    val model = NewPostViewModel
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFf8f8f8))
    ) {
        Box(
            modifier = Modifier.padding(vertical = 16.dp, horizontal = 18.dp)
        ) {
            NoticeScreenHeader("Modification List")
        }
        LazyColumn(
            modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 16.dp)
        ) {
            items(model.modificationList) { mod ->
                AddModificationItem(mod) { updatedMod ->
                    model.modificationList = model.modificationList.map { existingMod ->
                        if (existingMod.key == updatedMod.key) updatedMod else existingMod
                    }.toMutableList()
                }
                Spacer(modifier = Modifier.height(16.dp))
            }
            item {
                AddModificationButton {
                    model.modificationList += Modification(
                        key = Utils.generateRandomString(4),
                        name = "",
                        price = "0.0"
                    )
                }
            }
        }
    }
}

data class Modification(
    val key: String,
    val name: String,
    val price: String
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddModificationItem(modification: Modification, onUpdate: (Modification) -> Unit) {
    var isEditPriceBottomModalVisible by remember { mutableStateOf(false) }
    if (isEditPriceBottomModalVisible) {
        ModalBottomSheet(
            onDismissRequest = {
                isEditPriceBottomModalVisible = false
            },
            containerColor = Color.White,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            scrimColor = Color.Transparent,
            shape = RectangleShape
        ) {
            EditPriceBottomModal {
                isEditPriceBottomModalVisible = false
                onUpdate(
                    modification.copy(price = it)
                )
            }
        }
    }
    Column {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White)
                .padding(vertical = 13.dp, horizontal = 16.dp),


            ) {
            if (modification.name.isEmpty()) {
                Text("Please enter the name", fontSize = 14.sp, color = Color(0xFFd6d6d6))
            }
            BasicTextField(
                value = modification.name,
                onValueChange = {
                    onUpdate(
                        modification.copy(name = it)
                    )
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.Center)
            )
        }
        Spacer(modifier = Modifier.height(1.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White)
                .padding(top = 13.dp, bottom = 13.dp, start = 16.dp, end = 8.dp)
                .clickable {
                    isEditPriceBottomModalVisible = true
                }
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text("Price", fontSize = 16.sp)
                Spacer(modifier = Modifier.weight(1f))
                Text(modification.price, fontSize = 16.sp, color = Color(0xffda3832))
                Spacer(modifier = Modifier.width(6.dp))
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_nav_next),
                    contentDescription = "Edit",
                    modifier = Modifier.size(24.dp)
                )
            }
        }
    }
}

@Composable
fun AddModificationButton(onClick: () -> Unit = {}) {
    val stroke = Stroke(
        width = 2f,
        pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
    )
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(48.dp)
            .drawBehind {
                drawRoundRect(color = Color(0xFFd6d6d6), style = stroke)
            }
            .clickable {
                onClick()
            }
    ) {
        Image(
            painter = painterResource(id = R.drawable.rider_pro_new_post_add_pic),
            contentDescription = "Add",
            modifier = Modifier
                .size(24.dp)
                .align(Alignment.Center),
        )
    }
}

@Composable
fun EditPriceBottomModal(onOkClick: (String) -> Unit = {}) {
    val focusRequester = remember { FocusRequester() }
    val keyboardController = LocalSoftwareKeyboardController.current

    var text by remember { mutableStateOf("") }


    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }


    // Modal content including BasicTextField
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(16.dp)
    ) {
        Text("Price", fontSize = 16.sp)
        Spacer(modifier = Modifier.width(16.dp))
        BasicTextField(
            value = text,
            onValueChange = { text = it },
            modifier = Modifier
                .fillMaxWidth()
                .focusRequester(focusRequester),
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done
            ),
            singleLine = true,
            keyboardActions = KeyboardActions(
                onDone = {
                    keyboardController?.hide()
                    // Logic to close the dialog/modal
                    onOkClick(text)
                }
            ),
        )
    }
}