"use client";
import React, { useImperativeHandle } from "react";
import { Layer, Line } from "react-konva";
import type Konva from "konva";
import { ToolbarMode, Color } from "@/lib/Enums";

type LineType = {
    tool: ToolbarMode;
    color?: Color;
    points: {
        x: number;
        y: number;
    }[];
};

type LineLayerHandle = {
    handleMouseDown: () => void;
    handleMouseMove: () => void;
    handleMouseUp: () => void;
    clear: () => void;
};

type LineLayerProps = {
    stageRef: React.RefObject<Konva.Stage | null>;
    toolbarMode: ToolbarMode;
    color: Color;
};

const LineLayer = React.forwardRef<LineLayerHandle, LineLayerProps>(
    ({ stageRef, toolbarMode, color }, ref) => {
        const [lines, setLines] = React.useState<LineType[]>([]);
        const isDrawing = React.useRef(false);

        useImperativeHandle(ref, () => ({
            handleMouseDown() {
                console.log("Mouse Down in LineLayer");
                if (toolbarMode !== ToolbarMode.Draw && toolbarMode !== ToolbarMode.Erase) {
                    return;
                }

                isDrawing.current = true;

                const stage = stageRef.current?.getStage();
                const point = stage?.getPointerPosition();
                if (!point) {
                    return;
                }

                try {
                    const container = stage?.container();
                    if (container) {
                        container.tabIndex = 0;
                        container.focus();
                    }
                } catch {
                    // focus fallback best effort only
                }

                setLines(prev => [
                    ...prev,
                    { tool: toolbarMode, color: color, points: [{ x: point.x, y: point.y }] },
                ]);
            },

            handleMouseMove() {
                if (!isDrawing.current) {
                    return;
                }

                const point = stageRef.current?.getStage().getPointerPosition();
                if (!point) {
                    return;
                }

                setLines(prev => {
                    if (prev.length === 0) {
                        return prev;
                    }

                    const next = prev.slice();
                    const lastLine = { ...next[next.length - 1] };
                    lastLine.points = [...lastLine.points, { x: point.x, y: point.y }];
                    next[next.length - 1] = lastLine;
                    return next;
                });
            },
            handleMouseUp() {
                isDrawing.current = false;
            },
            clear() {
                // clear all lines
                setLines([]);
            },

        }));

        return (
            <Layer>
                {lines.map((line, idx) => (
                    <Line
                        key={idx}
                        points={line.points.flatMap(p => [p.x, p.y])}
                        stroke={line.color ?? "black"}
                        strokeWidth={line.tool === ToolbarMode.Erase ? 30 : 3}
                        tension={0.5}
                        lineCap="round"
                        lineJoin="round"
                        globalCompositeOperation={
                            line.tool === ToolbarMode.Erase ? "destination-out" : "source-over"
                        }
                    />
                ))}
            </Layer>
        );
    });

LineLayer.displayName = "LineLayer";

export default LineLayer;
export type { LineLayerProps, LineLayerHandle };