import { useEffect, useMemo, useRef, useState } from "react";
import { Image as KonvaImage, Rect, Group, Circle, Text as KonvaText } from "react-konva";
import Konva from "konva";
import useImage from "use-image";
import type { ShapeProps } from "./types";
import { createPortal } from "react-dom";
import { createRoundedRectClipFunc, getObjectBorderRadius } from "../../utils/borderRadius";

const VideoShape = ({
    obj,
    isSelected,
    onSelect,
    onUpdate,
    draggable,
}: ShapeProps) => {
    const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
    const [showVideoModal, setShowVideoModal] = useState(false);
    const groupRef = useRef<Konva.Group>(null);
    const [image] = useImage(thumbnailUrl || "");

    useEffect(() => {
        if (!obj.videoUrl) return;

        const video = document.createElement("video");
        video.src = obj.videoUrl;
        video.crossOrigin = "anonymous";
        video.muted = true;

        const handleLoadedMetadata = () => {
            video.currentTime = 0.1;
        };

        const handleSeeked = () => {
            const canvas = document.createElement("canvas");
            canvas.width = video.videoWidth || 400;
            canvas.height = video.videoHeight || 300;
            const ctx = canvas.getContext("2d");
            if (ctx) {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                const thumbnail = canvas.toDataURL("image/png");
                setThumbnailUrl(thumbnail);
            }
            video.removeEventListener("seeked", handleSeeked);
            video.removeEventListener("loadedmetadata", handleLoadedMetadata);
        };

        video.addEventListener("loadedmetadata", handleLoadedMetadata);
        video.addEventListener("seeked", handleSeeked);
        video.load();

        return () => {
            video.removeEventListener("seeked", handleSeeked);
            video.removeEventListener("loadedmetadata", handleLoadedMetadata);
        };
    }, [obj.videoUrl]);

    // Transformer is managed in EditorCanvas for multi-select support

    useEffect(() => {
        if (!showVideoModal) return;

        const handleEscape = (e: KeyboardEvent) => {
            if (e.key === "Escape") {
                setShowVideoModal(false);
            }
        };

        document.addEventListener("keydown", handleEscape);
        return () => {
            document.removeEventListener("keydown", handleEscape);
        };
    }, [showVideoModal]);

    const containerWidth = obj.width || 400;
    const containerHeight = obj.height || 300;
    const cornerRadius = getObjectBorderRadius(obj.borderRadius);
    const clipFunc = createRoundedRectClipFunc(containerWidth, containerHeight, cornerRadius);

    // هم‌تراز با viewer که object-fit: contain دارد
    const imageLayout = useMemo(() => {
        if (!image) {
            return { x: 0, y: 0, width: containerWidth, height: containerHeight };
        }

        const naturalWidth = image.width || 1;
        const naturalHeight = image.height || 1;
        const containerRatio = containerWidth / containerHeight;
        const imageRatio = naturalWidth / naturalHeight;

        let width: number;
        let height: number;
        if (imageRatio > containerRatio) {
            width = containerWidth;
            height = containerWidth / imageRatio;
        } else {
            height = containerHeight;
            width = containerHeight * imageRatio;
        }

        return {
            x: (containerWidth - width) / 2,
            y: (containerHeight - height) / 2,
            width,
            height,
        };
    }, [image, containerWidth, containerHeight]);

    const handlePlayClick = (e: Konva.KonvaEventObject<MouseEvent>) => {
        e.cancelBubble = true;
        const evt = e.evt;
        if (evt) {
            evt.stopPropagation();
            evt.stopImmediatePropagation();
            evt.preventDefault();
            evt.cancelBubble = true;
        }
        requestAnimationFrame(() => {
            setShowVideoModal(true);
        });
    };

    const handleGroupClick = (e?: Konva.KonvaEventObject<MouseEvent>) => {
        if (e) {
            const target = e.target;
            if (target.hasName("playButton") || target.getParent()?.hasName("playButton")) {
                return;
            }
        }
        if (groupRef.current) {
            onSelect(obj.id, groupRef.current, e);
        }
    };

    return (
        <>
            <Group
                ref={groupRef}
                id={obj.id}
                x={obj.x}
                y={obj.y}
                rotation={obj.rotation || 0}
                draggable={draggable}
                onClick={handleGroupClick}
                onDragEnd={(e) => {
                    const node = e.target;
                    onUpdate(obj.id, {
                        x: node.x(),
                        y: node.y(),
                    });
                }}

            >
                <Rect
                    width={containerWidth}
                    height={containerHeight}
                    fill="transparent"
                    cornerRadius={cornerRadius}
                    stroke={isSelected ? "#3b82f6" : "#666666"}
                    strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
                    onClick={handleGroupClick}
                />
                <Group clipFunc={clipFunc}>
                {image ? (
                    <>
                        <Rect
                            x={imageLayout.x}
                            y={imageLayout.y}
                            width={imageLayout.width}
                            height={imageLayout.height}
                            fill="#000000"
                            onClick={handleGroupClick}
                        />
                        <KonvaImage
                            x={imageLayout.x}
                            y={imageLayout.y}
                            width={imageLayout.width}
                            height={imageLayout.height}
                            image={image}
                            onClick={handleGroupClick}
                        />
                    </>
                ) : (
                    <Rect
                        x={0}
                        y={0}
                        width={containerWidth}
                        height={containerHeight}
                        fill="#1a1a1a"
                        onClick={handleGroupClick}
                    />
                )}
                </Group>
                <Group
                    name="playButton"
                    onClick={handlePlayClick}
                    onTap={handlePlayClick}
                    listening={true}
                >
                    <Circle
                        x={containerWidth / 2}
                        y={containerHeight / 2}
                        radius={30}
                        fill="rgba(0, 0, 0, 0.6)"
                        listening={false}
                    />
                    <KonvaText
                        x={containerWidth / 2}
                        y={containerHeight / 2}
                        text="▶"
                        fontSize={24}
                        fill="#ffffff"
                        fontFamily="Arial"
                        align="center"
                        verticalAlign="middle"
                        offsetX={12}
                        offsetY={12}
                        listening={false}
                    />
                </Group>
            </Group>
            {showVideoModal && createPortal(
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75"
                    onClick={() => setShowVideoModal(false)}
                >
                    <div
                        className="relative max-w-4xl w-full mx-4"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <button
                            onClick={() => setShowVideoModal(false)}
                            className="absolute -top-10 right-0 text-white text-2xl hover:text-gray-300"
                        >
                            ✕
                        </button>
                        <video
                            src={obj.videoUrl}
                            controls
                            autoPlay
                            className="w-full h-auto"
                        />
                    </div>
                </div>,
                document.body
            )}
        </>
    );
};

export default VideoShape;

