package com.rugvedsarika.landarea.ui.custom

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

class SketchView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private data class Stroke(val path: Path, val paint: Paint)

    private val strokes = mutableListOf<Stroke>()
    private var currentPath = Path()
    private var isEraserMode = false

    private val gridPaint = Paint().apply {
        color = Color.parseColor("#E0E0E0")
        strokeWidth = 1f
        style = Paint.Style.STROKE
    }

    private val drawPaint = Paint().apply {
        color = Color.BLACK
        isAntiAlias = true
        strokeWidth = 10f
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.ROUND
        strokeCap = Paint.Cap.ROUND
    }

    private val eraserPaint = Paint().apply {
        isAntiAlias = true
        strokeWidth = 50f
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.ROUND
        strokeCap = Paint.Cap.ROUND
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    }

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
    }

    fun setEraserMode(enabled: Boolean) {
        isEraserMode = enabled
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        // Draw Blueprint Grid
        val gridSize = 60f
        for (x in 0 until (width / gridSize).toInt() + 1) {
            canvas.drawLine(x * gridSize, 0f, x * gridSize, height.toFloat(), gridPaint)
        }
        for (y in 0 until (height / gridSize).toInt() + 1) {
            canvas.drawLine(0f, y * gridSize, width.toFloat(), y * gridSize, gridPaint)
        }
        
        // Draw existing strokes
        for (stroke in strokes) {
            canvas.drawPath(stroke.path, stroke.paint)
        }
        
        // Draw current path in progress
        val activePaint = if (isEraserMode) eraserPaint else drawPaint
        canvas.drawPath(currentPath, activePaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                currentPath.moveTo(x, y)
            }
            MotionEvent.ACTION_MOVE -> {
                currentPath.lineTo(x, y)
            }
            MotionEvent.ACTION_UP -> {
                val p = if (isEraserMode) {
                    Paint(eraserPaint)
                } else {
                    Paint(drawPaint)
                }
                strokes.add(Stroke(Path(currentPath), p))
                currentPath.reset()
            }
        }
        invalidate()
        return true
    }

    fun undo() {
        if (strokes.isNotEmpty()) {
            strokes.removeAt(strokes.size - 1)
            invalidate()
        }
    }

    fun clear() {
        strokes.clear()
        currentPath.reset()
        invalidate()
    }
}
