"use client";
import { widgetAlign, WidgetPosition } from "@/config/enums/tip-tap";
import { cn } from "@/lib/utils";
import { Camera, ChevronsLeftRight } from "lucide-react";
import Image from "next/image";
import { useState, useRef, useCallback } from "react";
import { BeforeAfterImageProps } from "../../types/types";

export default function BeforeAfterImageWidget({
    props,
    isNodeView = false
}: {
    props: BeforeAfterImageProps;
    isNodeView?: boolean;
}) {
    const [position, setPosition] = useState(50);
    const containerRef = useRef<HTMLDivElement>(null);

    const handlePointer = useCallback((clientX: number) => {
        const el = containerRef.current;
        if (!el) return;

        const { left, width } = el.getBoundingClientRect();
        const percent = ((clientX - left) / width) * 100;

        setPosition(Math.min(Math.max(percent, 0), 100));
    }, []);

    const onPointerDown = useCallback(
        (e: React.PointerEvent<HTMLDivElement>) => {
            const el = containerRef.current;
            if (!el) return;

            el.setPointerCapture(e.pointerId);

            handlePointer(e.clientX);

            const onMove = (ev: PointerEvent) => {
                handlePointer(ev.clientX);
            };

            const onUp = () => {
                el.releasePointerCapture(e.pointerId);
                window.removeEventListener("pointermove", onMove);
                window.removeEventListener("pointerup", onUp);
            };

            window.addEventListener("pointermove", onMove);
            window.addEventListener("pointerup", onUp);
        },
        [handlePointer]
    );

    if (!props?.mediaBefore?.length || !props?.mediaAfter?.length) {
        return null;
    }
    const { variant, mediaBefore, mediaAfter, labelBefore, labelAfter, caption, author } = props;

    const beforeMedia = mediaBefore[0];
    const afterMedia = mediaAfter[0];

    return (
        <div className={cn(!isNodeView && widgetAlign[variant])}>
            <div
                ref={containerRef}
                onPointerDown={onPointerDown}
                className="relative w-full touch-none overflow-hidden select-none"
            >
                <div className="relative block">
                    <span className="absolute top-2 right-2 bg-white px-1">{labelAfter}</span>
                    <Image
                        src={afterMedia.url}
                        alt={afterMedia.alt || caption || "artikelbillede"}
                        className="h-auto w-full"
                        width={1400}
                        height={800}
                    />
                </div>

                <div
                    className="absolute inset-0 h-full w-full object-cover"
                    style={{
                        clipPath: `inset(0 ${100 - position}% 0 0)`
                    }}
                >
                    <span className="absolute top-2 left-2 z-1 bg-white px-1">{labelBefore}</span>
                    <Image
                        src={beforeMedia.url}
                        alt={beforeMedia.alt || caption || "artikelbillede"}
                        className="h-full w-full object-cover"
                        width={1400}
                        height={800}
                    />
                </div>

                <div className="absolute top-0 h-full w-1 bg-white" style={{ left: `${position}%` }} />

                <div
                    aria-label="Sammenlign billeder"
                    className="absolute top-1/2 flex size-9 -translate-x-1/2 -translate-y-1/2 cursor-ew-resize items-center justify-center rounded-full bg-white leading-none shadow"
                    style={{ left: `${position}%` }}
                >
                    <ChevronsLeftRight className="size-6" />
                </div>
            </div>
            <div
                className={cn(
                    "mt-2 flex gap-2 font-serif text-neutral-500 xl:float-left xl:w-75 xl:pr-15",
                    variant === WidgetPosition.CENTER && "xl:float-none xl:w-full",
                    isNodeView && "text-xs xl:w-auto xl:pr-0"
                )}
            >
                {(caption || author) && (
                    <>
                        <Camera className="stroke-client-red fill-client-red inline-block size-3.5 shrink-0 [&>circle]:stroke-white [&>circle]:stroke-1" />
                        <span className="inline-block leading-[1.3]">
                            {caption.replaceAll("&shy;", "\u00AD")}{" "}
                            {author && <i className="text-xs">Fotograf: {author}</i>}
                        </span>
                    </>
                )}
            </div>
        </div>
    );
}
