import { selectors } from "@/store";
import styles from "./styles.module.scss";
import { useSelector } from "react-redux";
import { useCallback, useEffect, useRef, useState } from "react";
import { IPalmistryPoint } from "@/api/resources/Palmistry";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

function PalmPhoto() {
    const { translate } = useTranslations(ELocalesPlacement.CompatibilityV3);
    const photo = useSelector(selectors.selectCompatibilityV3Photo);
    const [isImageLoaded, setIsImageLoaded] = useState(false);
    const [imageWidth, setImageWidth] = useState(0);
    const [imageHeight, setImageHeight] = useState(0);
    const imageRef = useRef<HTMLImageElement>(null);
    const linesRef = useRef<SVGPathElement[]>([]);
    const fingers = useSelector(selectors.selectCompatibilityV3Fingers);
    const lines = useSelector(selectors.selectCompatibilityV3Lines);
    // const [textPositions, setTextPositions] = useState<Array<{ x: number, y: number }>>([]);

    useEffect(() => {
        if (isImageLoaded && imageRef.current) {
            setImageWidth(imageRef.current.width || 0);
            setImageHeight(imageRef.current.height || 0);
        }
    }, [isImageLoaded]);

    const getCoordinatesString = useCallback(
        (points: IPalmistryPoint[]) => {
            const coordinatesString = `M ${points[0]?.x * imageWidth} ${points[0]?.y * imageHeight
                }`;
            return points.reduce(
                (acc, point) =>
                    `${acc} L ${point?.x * imageWidth} ${point?.y * imageHeight}`,
                coordinatesString
            );
        },
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [lines, isImageLoaded, imageWidth, imageHeight]
    );

    const getLineLength = (line: SVGPathElement) => {
        return line?.getTotalLength();
    };

    // useEffect(() => {
    //     if (!imageWidth || !imageHeight || !lines.length) return;

    //     const textWidth = 90;
    //     const textHeight = 17;
    //     const padding = 10;
    //     const newPositions: Array<{ x: number, y: number }> = [];

    //     lines.forEach((line, index) => {
    //         const points = line.points;
    //         const positions = [];

    //         for (let i = 0; i < points.length - 1; i++) {
    //             const x = (points[i].x + points[i + 1].x) / 2;
    //             const y = (points[i].y + points[i + 1].y) / 2;
    //             positions.push({ x, y });
    //         }

    //         positions.unshift({ x: points[0].x, y: points[0].y });
    //         positions.push({ x: points[points.length - 1].x, y: points[points.length - 1].y });

    //         let positionFound = false;
    //         for (const pos of positions) {
    //             let hasOverlap = false;

    //             for (const existingPos of newPositions) {
    //                 if (
    //                     pos.x * imageWidth + padding < existingPos.x + textWidth &&
    //                     pos.x * imageWidth + padding + textWidth > existingPos.x &&
    //                     pos.y * imageHeight - padding < existingPos.y + textHeight &&
    //                     pos.y * imageHeight - padding + textHeight > existingPos.y
    //                 ) {
    //                     hasOverlap = true;
    //                     break;
    //                 }
    //             }

    //             if (!hasOverlap) {
    //                 newPositions.push({
    //                     x: pos.x * imageWidth + 10,
    //                     y: pos.y * imageHeight - 5
    //                 });
    //                 positionFound = true;
    //                 break;
    //             }
    //         }

    //         if (!positionFound) {
    //             newPositions.push({
    //                 x: points[0].x * imageWidth + textWidth + padding * (index + 1),
    //                 y: points[0].y * imageHeight - textHeight - padding * (index + 1)
    //             });
    //         }
    //     });

    //     setTextPositions(newPositions);
    // }, [lines, imageWidth, imageHeight]);

    return (
        <div className={styles.container}>
            <div className={styles.photoContainer}>
                <img
                    ref={imageRef}
                    className={styles.photo}
                    src={photo}
                    alt="Palm photo"
                    onLoad={() => setIsImageLoaded(true)}
                />
                {/* <div className={styles.blur}></div> */}
                {!!imageHeight && !!imageWidth && (
                    <svg
                        viewBox={`0 0 ${imageWidth} ${imageHeight}`}
                        className="scanned-photo__svg-objects"
                    >
                        {!!fingers.length &&
                            fingers?.map((finger, index) => {
                                return (
                                    <svg
                                        x={finger.point.x * imageWidth - 12}
                                        y={finger.point.y * imageHeight - 12}
                                        height="24px"
                                        width="24px"
                                        key={index}
                                    >
                                        <circle
                                            cx="50%"
                                            cy="50%"
                                            r="11"
                                            fill="white"
                                            opacity="0.3"
                                            className="scanned-photo__finger-point"
                                        />
                                        <circle
                                            cx="50%"
                                            cy="50%"
                                            r="5"
                                            fill="#066FDE"
                                            stroke="white"
                                            strokeWidth="0.3"
                                            className="scanned-photo__finger-point"
                                        />
                                    </svg>
                                );
                            })}

                        {lines.map((line, index) => (
                            <g key={`line-${index}`}>
                                <path
                                    className={`scanned-photo__line scanned-photo__line_${line?.name}`}
                                    d={getCoordinatesString(line?.points)}
                                    ref={(el) =>
                                        (linesRef.current[index] = el as SVGPathElement)
                                    }
                                    style={{
                                        strokeDasharray:
                                            getLineLength(linesRef.current[index]) || 500,
                                        strokeDashoffset:
                                            getLineLength(linesRef.current[index]) || 500,
                                    }}
                                />
                            </g>
                        ))}
                        {lines.map((line, index) => (
                            <g key={`line-label-${index}`}>
                                <text
                                    // x={textPositions[index]?.x || 0}
                                    // y={textPositions[index]?.y || 0}
                                    x={imageWidth - 10}
                                    y={index * 20 + 20}
                                    textAnchor="end"
                                    fill="#066FDE"
                                    className={`scanned-photo__line-text scanned-photo__line-text_${line?.name}`}
                                >
                                    {translate(`/try-app.palm_lines.${line.name}`)}
                                </text>
                            </g>
                        ))}
                    </svg>
                )}
            </div>
        </div>
    )
}

export default PalmPhoto