"use client";
import { useState, useEffect, forwardRef, useRef } from "react";
import {
  motion,
  AnimatePresence,
  useScroll,
  useTransform,
  Variants,
} from "framer-motion";
import { useInView } from "react-intersection-observer";
import Image from "next/image";
import StoryVisionBoard from "./storyVisionBoard";
import { getImageUrl } from "@/utils/imageHelper";

export type Story = {
  slug: string;
  visionFor: string;
  designHouse: string;
  coverTitle: string;
  title: string;
  subtitle: string;
  cover: string;
  visionSubtitle: string;
  drawingSubtitle: string;
  artisanSubtitle: string;
  finalSubtitle: string;
  drawingFront?: string;
  drawingBack: string;
  artisanBeginNote: string;
  artisanVideo: string;
  finalSketchImg: string;
  finalPieceImg: string;
  piecesGallery: {
    type: "image" | "video";
    src: string;
  }[];
  bottomSlides?: string[];
  visionBoard?: any;
  otherStories?: any[];
};

type StoryStepProps = {
  story: Story;
};

export default function StoryStepScroll({ story }: StoryStepProps) {
  const [activeSection, setActiveSection] = useState<
    | "vision"
    | "drawing"
    | "artisanNote"
    | "visionLifeText"
    | "artisanVideo"
    | "finalSketch"
    | "finalSketchDual"
    | "finalPiece"
    | "pieceGallery"
  >("vision");

  // Intersection Observer hooks
  const [visionRef, visionInView] = useInView({
    threshold: 0.2,
    triggerOnce: false,
  });
  const [drawingRef, drawingInView] = useInView({
    threshold: 0.2,
    triggerOnce: false,
  });
  const [artisanNoteRef, artisanNoteInView] = useInView({
    threshold: 0.2,
    triggerOnce: false,
  });
  const [artisanVideoRef, artisanVideoInView] = useInView({
    threshold: 0.2,
    triggerOnce: false,
  });
  const [finalSketchDualRef, finalSketchDualInView] = useInView({
    threshold: 0.1,
    triggerOnce: false,
  });
  const [finalPieceRef, finalPieceInView] = useInView({
    threshold: 0.2,
    triggerOnce: false,
  });
  const [pieceGalleryRef, pieceGalleryInView] = useInView({
    threshold: 0.5,
    triggerOnce: false,
  });

  // Update activeSection on scroll
  useEffect(() => {
    if (pieceGalleryInView) setActiveSection("pieceGallery");
    else if (finalPieceInView) setActiveSection("finalPiece");
    else if (finalSketchDualInView) setActiveSection("finalSketchDual");
    else if (artisanVideoInView) setActiveSection("artisanVideo");
    else if (artisanNoteInView) setActiveSection("artisanNote");
    else if (drawingInView) setActiveSection("drawing");
    else if (visionInView) setActiveSection("vision");
  }, [
    visionInView,
    drawingInView,
    artisanNoteInView,
    artisanVideoInView,
    finalSketchDualInView,
    finalPieceInView,
    pieceGalleryInView,
  ]);

  const rightVariants = {
    hidden: { opacity: 0, y: 25 },
    visible: { opacity: 1, y: 0, transition: { duration: 1.5 } },
  };

  const scrollRef = useRef<HTMLDivElement>(null);
  const [scrollTarget, setScrollTarget] = useState<HTMLElement | null>(null);

  useEffect(() => {
    if (scrollRef.current) setScrollTarget(scrollRef.current);
  }, []);

  const { scrollYProgress } = useScroll({ offset: ["start end", "end start"] });

  const rotate = useTransform(scrollYProgress, [0, 1], ["6deg", "-12deg"]);
  //===================  start code for drawing  =============================
  const drawingImgVariants: Variants = {
    hidden: { opacity: 0, scale: 2 },
    visible: (i: number | undefined) => ({
      opacity: 1,
      scale: 1,
      rotate: i === 0 ? -4 : 4,
      transition: {
        delay: (i ?? 0) * 2,
        duration: 1,
        ease: ["easeOut"],
      },
    }),
    exit: { opacity: 0, scale: 0.75 },
  };
  //===================  end code for drawing  ===============================
  //===================  start code for artisan Notes  =============================
  const opacity = useTransform(scrollYProgress, [0, 0.2, 0.8, 1], [0, 1, 1, 0]);
  const scale = useTransform(scrollYProgress, [0, 2, 1], [1.5, 1, 0.8]);
  const VisionTextopacity = useTransform(scrollYProgress, [0.3, 0.6], [0, 1]);
  const VisionTextscale = useTransform(scrollYProgress, [0.3, 0.6], [5, 1]);
  //===================  end code for artisan Notes  ===============================
  //===================  start code for final sketch n piece  =============================
  // Image 1 animations
  const xDualSnp = useTransform(scrollYProgress, [0, 1], ["80%", "-150%"]);
  const yDualSnp = useTransform(scrollYProgress, [0, 1], ["80%", "-150%"]);
  const xDualFnp = useTransform(scrollYProgress, [0, 1], ["-50%", "100%"]);
  const yDualFnp = useTransform(scrollYProgress, [0, 1], ["-50%", "100%"]);
  //===================  end code for final sketch n piece  =============================
  const xFnp = useTransform(scrollYProgress, [0, 1], ["150%", "-64%"]);
  const yFnp = useTransform(scrollYProgress, [0, 1], ["150%", "-100%"]);
  const scaleFnp = useTransform(scrollYProgress, [0, 1], [0, 2]);
  //===================  start code for final piece  =============================
  //===================  start code for final piece gallery  =============================
  const rotatefp1 = useTransform(scrollYProgress, [0, 1], ["6deg", "-20deg"]);
  const rotatefp2 = useTransform(scrollYProgress, [0, 1], ["-20deg", "12deg"]);
  const rotatefp3 = useTransform(scrollYProgress, [0, 1], ["-20deg", "8deg"]);
  const rotations = [rotatefp1, rotatefp2, rotatefp3];
  const fpgScale = useTransform(scrollYProgress, [0, 1], [1.25, 0.75]);
  //===================  End code for final piece gallery  =============================
  return (
    <div className="storyWrapper relative z-2 border-l-1 pt-4 md:pt-0">
      <div className="relative flex w-full flex-col pt-[16vh]">
        <div className="sticky top-[28%] z-10 h-[72vh] md:top-[10%] md:h-lvh">
          <div className="relative flex h-full items-end justify-end pb-[12vh]">
            <div className="mob-noise absolute -bottom-10 -left-[8%] z-10 h-[20vh] w-full bg-gray-100 md:hidden" />
            <div className="relative z-10 h-full w-full rotate-4 overflow-hidden border-1 bg-gray-100 p-1 md:w-[48%] md:rotate-4 md:p-4">
              <div className="absolute -top-[8%] -left-[25%] z-1 h-[36%] w-[60%] bg-[url('/images/butterfly-thred-gray.webp')] bg-cover opacity-20 md:w-[53%]" />
              <div className="absolute -right-[4%] -bottom-[8%] h-[32%] w-[32%] bg-[url('/fabric/thread-flower-open.png')] bg-cover opacity-20" />
              <div className="flex flex-col items-end justify-end pr-0 align-bottom md:pr-1">
                <div className="mr-2 flex flex-row border-b-1 pt-1 pb-0.5">
                  <div className="font-bogart relative top-1 pr-1 text-sm/4 md:text-lg/6">
                    <span className="capitalize">{story.visionFor}</span>
                    {"'s"}
                  </div>
                  <div className="w-20 md:w-24">
                    <Image
                      src="/images/morni-logo-black.svg"
                      alt="Morni Brand Logo"
                      width={200}
                      height={60}
                      className="img-responsive"
                    />
                  </div>
                </div>
                <div className="font-bogart hidden pr-2 text-xs md:text-sm">
                  by <span className="capitalize">{story.designHouse}</span>
                </div>
              </div>
              <AnimatePresence mode="wait">
                {activeSection === "vision" && (
                  <StoryVisionBoard visionBoard={story.visionBoard} />
                )}
                {activeSection === "drawing" &&
                  (story.drawingFront || story.drawingBack) && (
                    <div className="relative -top-[2%] flex h-full w-full items-center justify-center">
                      {story.drawingFront && (
                        <motion.div
                          custom={0}
                          variants={drawingImgVariants}
                          initial="hidden"
                          animate="visible"
                          exit="exit"
                          className="absolute inset-0 z-0 flex items-center justify-center p-0 md:p-2"
                        >
                          <div className="flex aspect-[4/5] w-4/5 items-center justify-center overflow-hidden border border-gray-950/25 bg-gray-100/90 align-middle">
                            <Image
                              src={getImageUrl(story.drawingFront)}
                              alt="Drawing Front Image"
                              width={800}
                              height={1000}
                              className="aspect-[4/5] h-full w-full object-contain object-center"
                            />
                          </div>
                        </motion.div>
                      )}
                      {story.drawingBack && (
                        <motion.div
                          custom={1}
                          variants={drawingImgVariants}
                          initial="hidden"
                          animate="visible"
                          exit="exit"
                          className="absolute inset-0 z-10 flex items-center justify-center p-0 md:p-2"
                        >
                          <div className="flex aspect-[4/5] w-4/5 items-center justify-center overflow-hidden border border-gray-950/25 bg-gray-100 align-middle">
                            <Image
                              src={getImageUrl(story.drawingBack)}
                              alt="Drawing Back Image"
                              width={800}
                              height={1000}
                              className="aspect-[4/5] h-full w-full object-contain object-center"
                            />
                          </div>
                        </motion.div>
                      )}
                    </div>
                  )}
                {activeSection === "artisanNote" && (
                  <div className="relative mx-auto flex w-full items-center justify-center align-middle">
                    <motion.div
                      key="artisanNote"
                      initial={{ opacity: 0, scale: 3, rotate: "-6deg" }}
                      animate={{
                        opacity: 1,
                        scale: 1,
                        rotate: 0,
                        transition: { duration: 1, ease: "linear" },
                      }}
                      exit={{
                        opacity: 0,
                        scale: 0.25,
                        transition: { duration: 1, ease: "linear" },
                      }}
                      className="relative z-2 w-full aspect-[4/5] p-2 md:p-12 mt-4 md:-mt-8"
                    >
                      <div className="border border-gray-950/25">
                        <Image
                          src={getImageUrl(story.artisanBeginNote)}
                          alt="Artisan note"
                          width={800}
                          height={1000}
                          className="img-responsive"
                        />
                      </div>
                    </motion.div>
                  </div>
                )}
                {activeSection === "artisanVideo" && story.artisanVideo && (
                  <div className="relative -top-[4%] flex h-full flex-col p-0 md:p-4">
                    <div className="inset-0 flex h-full w-full flex-col items-center justify-center pt-4 md:pt-8 align-middle">
                      <div className="flex aspect-square w-[88%] flex-col border">
                        <video
                          src={getImageUrl(story.artisanVideo)}
                          controls={false}
                          muted
                          autoPlay
                          loop
                          playsInline
                          className="aspect-4/5 h-auto w-full object-cover object-center"
                        />
                      </div>
                    </div>
                  </div>
                )}
                {activeSection === "finalPiece" && (
                  <div className="relative flex aspect-[4/5] w-full items-center justify-center align-middle">
                    <motion.div
                      key="finalPiece"
                      initial={{ opacity: 0, scale: 3, rotate: "-6deg" }}
                      animate={{
                        opacity: 1,
                        scale: 1,
                        rotate: 0,
                        transition: { duration: 1, ease: "linear" },
                      }}
                      exit={{
                        opacity: 0,
                        scale: 0.5,
                        transition: { duration: 0.5, ease: "linear" },
                      }}
                      className="relative z-2 w-full p-0 md:p-4"
                    >
                      <div className="flex w-full p-4 mt-8 items-center justify-center align-middle">
                        <div className="flex aspect-[4/5] w-full md:w-9/10 items-center justify-center border border-gray-950/25 align-middle">
                          <Image
                            src={getImageUrl(story.finalPieceImg)}
                            alt="Final Piece"
                            width={800}
                            height={1000}
                            className="h-full w-full object-cover object-center"
                          />
                        </div>
                      </div>
                    </motion.div>
                  </div>
                )}

                {activeSection === "pieceGallery" && (
                  <motion.div
                    key="pieceGallery"
                    variants={rightVariants}
                    initial="hidden"
                    animate="visible"
                    exit="hidden"
                    style={{ scale: fpgScale }}
                  >
                    <div className="relative z-10 mt-4 h-[88vh] w-full p-1 md:h-[90vh] md:p-2">
                      {story.piecesGallery?.slice(0, 3).map((item, index) => {
                        let styleClass = "";
                        if (index === 0)
                          styleClass = "w-[44%] z-2 top-2 md:-top-[180%]";
                        else if (index === 1)
                          styleClass =
                            "w-[48%] md:w-[52%] left-auto right-4 md:right-0 -top-[50%] z-1";
                        else if (index === 2)
                          styleClass =
                            "w-[56%] md:w-[48%] left-[20%] top-[450%] md:top-[800%] z-3";
                        else styleClass = "bg-gray-100";

                        const rotateValue = rotations[index] || "15deg";

                        return (
                          <div
                            key={index}
                            className="relative p-[4%] md:p-[2%]"
                          >
                            <motion.div
                              className={`absolute bg-white p-1.5 pb-6 shadow-2xl md:p-2 md:pb-12 ${styleClass}`}
                              style={{ rotate: rotateValue }}
                            >
                              <div className="relative aspect-[4/5] w-full overflow-hidden border">
                                {item.type === "image" ? (
                                  <Image
                                    src={getImageUrl(item.src)}
                                    alt={`Final piece ${index + 1}`}
                                    width={800}
                                    height={1000}
                                    className="aspect-4/5 h-full w-full object-cover object-center"
                                  />
                                ) : item.type === "video" ? (
                                  <video
                                    src={getImageUrl(item.src)}
                                    controls={false}
                                    muted
                                    autoPlay
                                    loop
                                    playsInline
                                    className="aspect-4/5 h-auto w-full object-cover"
                                  />
                                ) : null}
                                <div className="mob-noise absolute top-0 left-0 h-full w-full opacity-50" />
                              </div>
                            </motion.div>
                          </div>
                        );
                      })}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </div>
        </div>
        <div className="relative -top-[60vh]">
          <Section
            ref={visionRef}
            title="The Vision"
            subtitle={story.visionSubtitle}
            iconName="icon-vision-eye"
            iconClass="-left-8 md:-left-15 -top-3 md:-top-6 h-12 w-20 md:h-20 md:w-34 -rotate-12"
            sdStyle="pt-0 pb-150 max-w-80 z-1"
          />
          {(story.drawingFront || story.drawingBack) && (
            <Section
              ref={drawingRef}
              title={
                <>
                  Drawing it
                  <br />
                  into Form
                </>
              }
              subtitle={story.drawingSubtitle}
              iconName="icon-bright-idea"
              iconClass="-left-8 md:-left-14 -top-5 md:-top-8 h-20 w-21 md:h-31 md:w-32 -rotate-12"
              sdStyle="min-h-[80vh] pb-[80vh] md:pb-120 max-w-80"
            />
          )}
          {story.artisanBeginNote && (
            <Section
              ref={artisanNoteRef}
              title={
                <>
                  Artisans
                  <br />
                  Begin
                  <br />
                  Crafting
                </>
              }
              subtitle={story.artisanSubtitle}
              iconName="icon-begin-crafting"
              iconClass="-left-6 md:-left-13 -top-3 md:-top-8 h-22 w-16 md:h-39 md:w-28"
              sdStyle="pt-[10vh] md:pt-[80vh] pb-[40vh] mb:pb-[20vh] max-w-80"
            />
          )}
          {story.artisanVideo && (
            <Section
              ref={artisanVideoRef}
              title=""
              subtitle=""
              iconName=""
              iconClass=""
              sdStyle="pt-[10vh] md:pt-[10vh] pb-[20vh] min-h-[50vh] max-w-80"
            />
          )}
          {story.finalPieceImg && (
            <Section
              ref={finalPieceRef}
              title=""
              subtitle=""
              iconName=""
              iconClass=""
              sdStyle="pt-[10vh] md:pt-[80vh] pb-[40vh] mb:pb-[20vh] max-w-80"
            />
          )}

          <Section
            ref={pieceGalleryRef}
            title={
              <>
                The Final
                <br />
                Piece
              </>
            }
            subtitle={story.finalSubtitle}
            iconName="icon-bud-flower-thread"
            iconClass="-left-7 md:-left-12.5 md:-top-6 h-18 w-19 md:h-29 md:w-30"
            sdStyle="pt-[80vh] pb-[20vh] min-h-[80vh] max-w-80"
          />
        </div>
      </div>
    </div>
  );
}

const Section = forwardRef<
  HTMLDivElement,
  {
    title: React.ReactNode;
    subtitle: string;
    iconName: string;
    iconClass: string;
    sdStyle: string;
  }
>(({ title, subtitle, iconName, iconClass, sdStyle }, ref) => (
  <div ref={ref} className={`relative ${sdStyle}`}>
    <div className="absolute top-[10%] -left-1 z-3 flex h-[80%] w-1.5 flex-col justify-between">
      {[3, 6, 3, 3].map((height, i) => (
        <span
          key={i}
          className={`hairline inline-flex h-${height} w-full bg-gray-950`}
        />
      ))}
    </div>
    <div className="flex flex-col gap-2">
      <div className="relative -left-2 flex flex-row items-center align-middle">
        <div className={`${iconName} ${iconClass} absolute bg-gray-950/25`} />
        {title && (
          <div>
            <span className="flex h-4 w-4 flex-col items-center justify-center rounded-full border-2 bg-gray-100 align-middle">
              <i className="flex h-2 w-2 rounded-full bg-gray-950"></i>
            </span>
          </div>
        )}

        <h2 className="storyTitle relative top-2 pl-8 md:top-1 md:pl-10">
          {title}
        </h2>
      </div>
      <p className="storySubTitle hidden pl-12 md:flex">{subtitle}</p>
    </div>
  </div>
));

Section.displayName = "Section";
