import { ChevronLeftIcon, ChevronRightIcon } from "@radix-ui/react-icons";
import React, { useRef, useCallback } from "react";
import HTMLFlipBook from "react-pageflip";

interface FlipbookProps {
  children: React.ReactNode[];
  width: number;
  height: number;
  className?: React.ComponentProps<"div">["className"];
}

interface PageFlip {
  getCurrentPageIndex(): number;
  getPageCount(): number;
  flip(page: number): void;
  flipPrev(): void;
  flipNext(): void;
}

export default function Flipbook(props: FlipbookProps) {
  const flipbook = useRef<{ pageFlip(): PageFlip } | null>(null);

  // Function to flip pages
  const flipPage = useCallback(
    (direction: "next" | "prev") => {
      const flipbookCurrent = flipbook.current;
      if (flipbookCurrent) {
        const pageFlipObj = flipbookCurrent.pageFlip();
        const currentPageIndex = pageFlipObj.getCurrentPageIndex();
        const pageCount = pageFlipObj.getPageCount();

        if (direction === "next") {
          if (currentPageIndex + 2 === pageCount) {
            pageFlipObj.flip(0);
          } else {
            pageFlipObj.flipNext();
          }
        } else if (direction === "prev") {
          if (currentPageIndex === 0) {
            pageFlipObj.flip(pageCount - 1);
          } else {
            pageFlipObj.flipPrev(); // Add this method to handle the previous page flip
          }
        }
      }
    },
    [flipbook],
  );

  // Handler for the next button
  const nextButtonClick = useCallback(() => {
    flipPage("next");
  }, [flipPage]);

  // Handler for the previous button
  const prevButtonClick = useCallback(() => {
    flipPage("prev");
  }, [flipPage]);

  return (
    <div className={`flex items-center justify-center ${props.className}`}>
      <button onClick={prevButtonClick}>
        <ChevronLeftIcon
          height={50}
          width={50}
          className="max-h-[7vw] max-w-[7vw]"
        />
      </button>
      <HTMLFlipBook
        usePortrait={false}
        className="text-black"
        width={props.width}
        height={props.height}
        size="fixed"
        style={{}}
        minHeight={100}
        maxHeight={500}
        minWidth={100}
        maxWidth={500}
        startPage={0}
        startZIndex={0}
        drawShadow
        flippingTime={1000}
        autoSize
        maxShadowOpacity={1}
        showCover={false}
        mobileScrollSupport
        clickEventForward
        useMouseEvents
        swipeDistance={20}
        showPageCorners
        disableFlipByClick={false}
        ref={flipbook}
      >
        {props.children}
      </HTMLFlipBook>
      <button onClick={nextButtonClick}>
        <ChevronRightIcon
          height={50}
          width={50}
          className="max-h-[7vw] max-w-[7vw]"
        />
      </button>
    </div>
  );
}
