package com.aiosman.ravenow.ui.composables

import android.graphics.BitmapFactory
import android.util.Base64
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.material.AlertDialog
import androidx.compose.material.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.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.api.CaptchaResponseBody
import java.io.ByteArrayInputStream

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ClickCaptchaView(
    captchaData: CaptchaResponseBody,
    onPositionClicked: (Offset) -> Unit
) {
    var clickPositions by remember { mutableStateOf(listOf<Offset>()) }

    val context = LocalContext.current
    val imageBitmap = remember(captchaData.masterBase64) {
        val decodedString = Base64.decode(captchaData.masterBase64, Base64.DEFAULT)
        val inputStream = ByteArrayInputStream(decodedString)
        BitmapFactory.decodeStream(inputStream).asImageBitmap()
    }
    val thumbnailBitmap = remember(captchaData.thumbBase64) {
        val decodedString = Base64.decode(captchaData.thumbBase64, Base64.DEFAULT)
        val inputStream = ByteArrayInputStream(decodedString)
        BitmapFactory.decodeStream(inputStream).asImageBitmap()
    }
    var boxWidth by remember { mutableStateOf(0) }
    var boxHeightInDp by remember { mutableStateOf(0.dp) }
    var scale by remember { mutableStateOf(1f) }
    val density = LocalDensity.current
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {

        Text(stringResource(R.string.captcha_hint))
        Spacer(modifier = Modifier.height(16.dp))
        Image(
            bitmap = thumbnailBitmap,
            contentDescription = null,
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .onGloballyPositioned {
                    boxWidth = it.size.width
                    scale = imageBitmap.width.toFloat() / boxWidth
                    boxHeightInDp = with(density) { (imageBitmap.height.toFloat() / scale).toDp() }
                }
                .background(Color.Gray)
        ) {
            if (boxWidth != 0 && boxHeightInDp != 0.dp) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(boxHeightInDp)
                ) {
                    Image(
                        bitmap = imageBitmap,
                        contentDescription = null,
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .fillMaxSize()
                            .pointerInteropFilter { event ->
                                if (event.action == android.view.MotionEvent.ACTION_DOWN) {
                                    val newPosition = Offset(event.x, event.y)
                                    clickPositions = clickPositions + newPosition
                                    // 计算出点击的位置在图片上的坐标
                                    val imagePosition = Offset(
                                        newPosition.x * scale,
                                        newPosition.y * scale
                                    )
                                    onPositionClicked(imagePosition)
                                    true
                                } else {
                                    false
                                }
                            }
                    )

                    // Draw markers at click positions
                    clickPositions.forEachIndexed { index, position ->
                        Canvas(modifier = Modifier.fillMaxSize()) {
                            drawCircle(
                                color = Color(0xaada3832).copy(),
                                radius = 40f,
                                center = position
                            )
                            drawContext.canvas.nativeCanvas.apply {
                                drawText(
                                    (index + 1).toString(),
                                    position.x,
                                    position.y + 15f, // Adjusting the y position to center the text
                                    android.graphics.Paint().apply {
                                        color = android.graphics.Color.WHITE
                                        textSize = 50f
                                        textAlign = android.graphics.Paint.Align.CENTER
                                    }
                                )
                            }
                        }
                    }
                }
            }

        }
    }

}

@Composable
fun ClickCaptchaDialog(
    captchaData: CaptchaResponseBody,
    onLoadCaptcha: () -> Unit,
    onDismissRequest: () -> Unit,
    onPositionClicked: (Offset) -> Unit
) {
    AlertDialog(
        onDismissRequest = {
            onDismissRequest()
        },
        title = {
            Text(stringResource(R.string.captcha))
        },
        text = {
            Column {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    ClickCaptchaView(
                        captchaData = captchaData,
                        onPositionClicked = onPositionClicked
                    )
                }
                Spacer(modifier = Modifier.height(16.dp))

                ActionButton(
                    text = stringResource(R.string.refresh),
                    modifier = Modifier
                        .fillMaxWidth(),
                ) {
                    onLoadCaptcha()
                }
            }
        },
        confirmButton = {

        },
    )
}

