package com.isidroid.ui.print_job._components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp


@Composable
internal fun ColorizedComponent(isColor: Boolean, modifier: Modifier) {
    Card(
        modifier = modifier,
        shape = RoundedCornerShape(8.dp)
    ) {
        if (isColor)
            SquareRGBGradientComponent()
        else
            CircularHalfBlackHalfWhite()
    }
}

@Composable
private fun CircularHalfBlackHalfWhite() {
    Box(
        modifier = Modifier
    ) {
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawRectWithGradient(
                startColor = Color.Black,
                endColor = Color.White,
                startX = 0f,
                startY = 0f,
                width = size.width,
                height = size.height
            )
        }
    }
}

@Composable
private fun SquareRGBGradientComponent() {
    Box(
        modifier = Modifier
    ) {
        Canvas(modifier = Modifier.fillMaxSize()) {
            // Draw Blue to Red gradient (right side)
            drawRectWithGradient(
                startColor = Color.Blue,
                endColor = Color.Red,
                startX = 0f,
                startY = 0f,
                width = size.width,
                height = size.height
            )
        }
    }
}

/**
 * Helper function to draw a rectangle with a linear gradient from startColor to endColor.
 */
private fun DrawScope.drawRectWithGradient(
    startColor: Color,
    endColor: Color,
    startX: Float,
    startY: Float,
    width: Float,
    height: Float
) {
    drawRect(
        brush = androidx.compose.ui.graphics.Brush.linearGradient(
            colors = listOf(startColor, endColor),
            start = Offset(startX, startY),
            end = Offset(startX + width, startY + height)
        ),
        topLeft = Offset(startX, startY),
        size = androidx.compose.ui.geometry.Size(width, height)
    )
}

@Composable
@Preview
private fun ColorizedComponentPreview() {
    Surface {
        Column {
            ColorizedComponent(isColor = true, modifier = Modifier.size(120.dp))
            ColorizedComponent(isColor = false, modifier = Modifier.size(120.dp))
        }
    }
}