import { Head, Link, router } from '@inertiajs/react';
import AppLayout from '@/Layouts/AppLayout.jsx';
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb.jsx";
import { Button } from "@/components/ui/button.jsx";
import { ChevronFirst, ChevronLast, Rows3, Settings } from "lucide-react";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog";
import PrimaryButton from "@/components/PrimaryButton.jsx";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipProvider, TooltipTrigger } from "@radix-ui/react-tooltip";
import { TooltipContent } from "@/components/ui/tooltip.jsx";
import { throttle } from "lodash";

export default function Read({ auth, comic, chapter }) {
    const [readingMode, setReadingMode] = useState('rtl'); // rtl, utd
    const [isTwoPagesPerScreen, setIsTwoPagePerScreen] = useState(false);
    const [currentImage, setCurrentImage] = useState(1);

    const windowSize = useWindowSize();
    const ref = useRef();

    const [divDimensions, setDivDimensions] = useState([0, 0]);

    const [loading, setLoading] = useState(true);

    function useWindowSize() {
        const [size, setSize] = useState([0, 0]);
        useLayoutEffect(() => {
            function updateSize() {
                setSize([window.innerWidth, window.innerHeight]);
            }

            window.addEventListener('resize', updateSize);
            updateSize();
            return () => window.removeEventListener('resize', updateSize);
        }, []);

        return size;
    }

    const toggleReadingMode = (e) => {
        if (e) {
            setReadingMode('utd');
        } else {
            setReadingMode('rtl');
        }
    }

    const setViewPort = (e) => {
        //console.log(e.target.childNodes);
        //console.log(e.target.naturalHeight);
    }

    const ImageForComic = (img) => {
        const imgRef = useRef();

        const resizeImage = () => {
            if (!imgRef.current || !ref.current) return;

            const { naturalWidth, naturalHeight } = imgRef.current;
            const containerWidth = ref.current.clientWidth;
            const containerHeight = ref.current.clientHeight;

            let width, height;

            if (readingMode === "rtl") {
                // Scale for RTL mode
                const ratioWidth = naturalWidth / containerWidth;
                const ratioHeight = naturalHeight / containerHeight;
                const maxRatio = Math.max(ratioWidth, ratioHeight);
                width = naturalWidth / maxRatio;
                height = naturalHeight / maxRatio;
            } else if (readingMode === "utd") {
                // Scale for UTD mode
                const ratio = divDimensions[1] < divDimensions[0] ? 0.33 : 1; // Example logic
                const scaledWidth = containerWidth * ratio;
                const scaledRatio = naturalWidth / scaledWidth;
                width = naturalWidth / scaledRatio;
                height = naturalHeight / scaledRatio;
            }

            // Apply dimensions directly
            imgRef.current.style.width = `${width}px`;
            imgRef.current.style.height = `${height}px`;
        };

        useEffect(() => {
            resizeImage();
        }, [readingMode, divDimensions]); // Recalculate when these dependencies change

        const handleImageClick = (e) => {
            if (readingMode === "utd") return;

            const bounds = imgRef.current.getBoundingClientRect();
            const percentage = (e.pageX - bounds.left) / imgRef.current.offsetWidth;

            if (percentage < 0.45) {
                if (img.innerKey === 0 && chapter.chapter.prev) {
                    router.visit(route('comics.read', [comic.comic.path_word, chapter.chapter.prev]));
                } else {
                    document.getElementById(`image-${img.innerKey - 1}`)?.scrollIntoView();
                }
            } else if (percentage > 0.55) {
                if (img.innerKey >= chapter.sorted.length - 1 && chapter.chapter.next) {
                    router.visit(route('comics.read', [comic.comic.path_word, chapter.chapter.next]));
                } else {
                    document.getElementById(`image-${img.innerKey + 1}`)?.scrollIntoView();
                }
            }
        };

        return (<div className="basis-full">
            <img
                id={ `image-${img.innerKey}` }
                ref={ imgRef }
                className="m-auto comic-img"
                src={ `/image/${btoa(img.url)}` }
                onLoad={ resizeImage } // Resize image immediately on load
                onClick={ handleImageClick }
                alt={ comic.comic.name }
            />
        </div>);
    }

    const Toolbar = () => {
        return (
            <>
                <Dialog>
                    <DialogTrigger>
                        <TooltipProvider>
                            <Tooltip>
                                <TooltipTrigger>
                                    <Button variant="link" size="icon">
                                        <Settings />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p>Options</p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>
                    </DialogTrigger>
                    <DialogContent className="max-w-[600px]">
                        <DialogHeader>
                            <DialogTitle>Options</DialogTitle>
                            <DialogDescription>

                            </DialogDescription>
                        </DialogHeader>
                        <div className="space-y-4">
                            <div className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
                                <div className="space-y-0.5">
                                    <label>Reading Mode</label>
                                    <p>Turn on for UTD mode</p>
                                </div>
                                <Switch defaultChecked={ readingMode === "utd" }
                                        onCheckedChange={ (e) => toggleReadingMode(e) } />
                            </div>
                        </div>
                        <DialogFooter>
                            <DialogClose asChild>
                                <PrimaryButton>Done</PrimaryButton>
                            </DialogClose>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>

                <TooltipProvider>
                    <Tooltip>
                        <TooltipTrigger>
                            <Button variant="link" size="icon" asChild>
                                <Link href={ route('comics.chapters', [comic.comic.path_word]) }>
                                    <Rows3 />
                                </Link>
                            </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                            <p>Content Page</p>
                        </TooltipContent>
                    </Tooltip>
                </TooltipProvider>

                { chapter.chapter.prev && (
                    <TooltipProvider>
                        <Tooltip>
                            <TooltipTrigger>
                                <Button variant="link" size="icon" asChild>
                                    <Link href={ route('comics.read', [comic.comic.path_word, chapter.chapter.prev]) }>
                                        <ChevronFirst />
                                    </Link>
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>
                                <p>Previous Chapter</p>
                            </TooltipContent>
                        </Tooltip>
                    </TooltipProvider>
                ) }

                { chapter.chapter.next && (
                    <TooltipProvider>
                        <Tooltip>
                            <TooltipTrigger>
                                <Button variant="link" size="icon" asChild>
                                    <Link href={ route('comics.read', [comic.comic.path_word, chapter.chapter.next]) }>
                                        <ChevronLast />
                                    </Link>
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>
                                <p>Next Chapter</p>
                            </TooltipContent>
                        </Tooltip>
                    </TooltipProvider>
                ) }

                <Button variant="ghost">
                     { currentImage } / { chapter.sorted.length }
                </Button>
            </>
        );
    }

    useEffect(() => {
        setDivDimensions([ref.current.clientWidth, ref.current.clientHeight]);
    }, [windowSize]);

    useEffect(() => {
        if (!ref.current) return;

        const handleScroll = () => {
            const containerScrollTop = ref.current.scrollTop; // Current scroll position of the container
            const images = ref.current.querySelectorAll("img"); // Get all images

            let visibleImageIndex = 0;

            // Determine which image is visible based on scroll position
            images.forEach((image, index) => {
                const imageTop = image.offsetTop; // Distance from top of the container
                const imageBottom = imageTop + image.offsetHeight;

                // Check if the image is in the visible area
                if (containerScrollTop + 80 >= imageTop && containerScrollTop < imageBottom) {
                    visibleImageIndex = index;
                }
            });

            // Update the current image index
            setCurrentImage(visibleImageIndex + 1);
        };

        const throttledHandleScroll = throttle(handleScroll, 100); // Throttle for performance
        ref.current.addEventListener("scroll", throttledHandleScroll);

        // Initial check for visible image
        handleScroll();

        return () => {
            if (ref.current) {
                ref.current.removeEventListener("scroll", throttledHandleScroll);
            }
        };
    }, []);

    return (
        <AppLayout auth={ auth } header={
            <>
                <BreadcrumbSeparator />
                <BreadcrumbItem>
                    <BreadcrumbLink asChild>
                        <Link href={ route('comics.chapters', [comic.comic.path_word]) }>
                            { comic.comic.name }
                        </Link>
                    </BreadcrumbLink>
                </BreadcrumbItem>
                <BreadcrumbSeparator />
                <BreadcrumbItem>
                    <BreadcrumbPage>{ chapter.chapter.name }</BreadcrumbPage>
                </BreadcrumbItem>
            </>
        } toolbar={ <Toolbar /> }>
            <Head>
                <title>{ chapter.chapter.name } - { comic.comic.name }</title>
            </Head>
            <div className="p-3 pt-1 pb-1 flex flex-wrap justify-center" id="mvp" ref={ ref }
                 style={ { overflowAnchor: "none", height: "calc(100dvh - 90px)", overflowY: "scroll" } }>
                { chapter.sorted.map((img, j) => <ImageForComic key={ j } innerKey={ j } { ...img } />) }
            </div>
        </AppLayout>
    );
}
