import React, { useState, useCallback, useMemo, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";

enum ScreenSize {
  MOBILE = "mobile",
  TABLET = "tablet",
  WEB = "web",
}

interface ProjectImage {
  id: string;
  title: string;
  subtitle: string;
  screenSize: ScreenSize;
  href: string;
}

interface Project {
  id: number;
  name: string;
  description: string;
  images: ProjectImage[];
}

interface ProjectGroup {
  id: number;
  name: string;
  projects: Project[];
}

// Image dimensions in pixels
const IMAGE_WIDTH = 383;
const IMAGE_HEIGHT = 852;

const projectGroupsData: ProjectGroup[] = [
  {
    id: 1,
    name: "Nature",
    projects: [
      {
        id: 201,
        name: "Mountain Vista",
        description: "Breathtaking view of mountain ranges",
        images: [
          {
            id: "201-web",
            title: "Mountain Peak",
            subtitle: "Snowy caps",
            screenSize: ScreenSize.WEB,
            href: `https://picsum.photos/id/201/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
          {
            id: "201-mobile",
            title: "Mountain Mobile",
            subtitle: "Compact view",
            screenSize: ScreenSize.MOBILE,
            href: `https://picsum.photos/id/202/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
        ],
      },
      {
        id: 202,
        name: "Serene Lake",
        description: "Calm waters reflecting surrounding nature",
        images: [
          {
            id: "202-web",
            title: "Lake View",
            subtitle: "Mirror-like surface",
            screenSize: ScreenSize.WEB,
            href: `https://picsum.photos/id/203/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
          {
            id: "202-mobile",
            title: "Lake Mobile",
            subtitle: "Vertical panorama",
            screenSize: ScreenSize.MOBILE,
            href: `https://picsum.photos/id/204/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
        ],
      },
    ],
  },
  {
    id: 2,
    name: "Architecture",
    projects: [
      {
        id: 301,
        name: "Modern Skyscraper",
        description: "Sleek design of urban architecture",
        images: [
          {
            id: "301-web",
            title: "Skyscraper View",
            subtitle: "City skyline",
            screenSize: ScreenSize.WEB,
            href: `https://picsum.photos/id/301/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
          {
            id: "301-mobile",
            title: "Skyscraper Mobile",
            subtitle: "Vertical view",
            screenSize: ScreenSize.MOBILE,
            href: `https://picsum.photos/id/302/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
        ],
      },
      {
        id: 302,
        name: "Historic Bridge",
        description: "Iconic bridge with classic architecture",
        images: [
          {
            id: "302-web",
            title: "Bridge Span",
            subtitle: "Engineering marvel",
            screenSize: ScreenSize.WEB,
            href: `https://picsum.photos/id/303/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
          {
            id: "302-mobile",
            title: "Bridge Mobile",
            subtitle: "Vertical perspective",
            screenSize: ScreenSize.MOBILE,
            href: `https://picsum.photos/id/304/${IMAGE_WIDTH}/${IMAGE_HEIGHT}`,
          },
        ],
      },
    ],
  },
];

const GroupedWheelControlledCarousel = () => {
  const itemGroups = useMemo(
    () =>
      projectGroupsData.map((group) => ({
        id: group.id,
        name: group.name,
        items: group.projects.flatMap((project) =>
          project.images.map((image) => ({
            id: image.id,
            item: image.href,
            title: image.title,
            subtitle: image.subtitle,
            projectName: project.name,
            projectDescription: project.description,
            screenSize: image.screenSize,
          })),
        ),
      })),
    [],
  );

  const flattenedItems = useMemo(
    () =>
      itemGroups.flatMap((group) =>
        group.items.map((item, idx) => ({
          ...item,
          groupId: group.id,
          groupName: group.name,
          id: `${group.id}-${idx}`,
        })),
      ),
    [itemGroups],
  );

  const totalItems = flattenedItems.length;
  const [visibleItemCount, setVisibleItemCount] = useState(7);
  const [containerWidth, setContainerWidth] = useState(600);
  const [containerHeight, setContainerHeight] = useState(200);

  const [offset, setOffset] = useState(0);

  useEffect(() => {
    const handleWheel = (event: WheelEvent) => {
      event.preventDefault();
      const delta = event.deltaX * 0.005; // Reduced multiplier for smoother scrolling
      setOffset((prevOffset) => {
        const newOffset = prevOffset + delta;
        return newOffset - Math.floor(newOffset / totalItems) * totalItems;
      });
    };

    window.addEventListener("wheel", handleWheel, { passive: false });

    return () => {
      window.removeEventListener("wheel", handleWheel);
    };
  }, [totalItems]);

  const visibleItems = useMemo(() => {
    const items = [];
    const halfVisible = Math.floor(visibleItemCount / 2);

    for (let i = -halfVisible; i <= halfVisible; i++) {
      const itemIndex = Math.floor(offset + i);
      const wrappedIndex = ((itemIndex % totalItems) + totalItems) % totalItems;
      const item = flattenedItems[wrappedIndex];

      const position = (i - (offset % 1)) / halfVisible;

      // Calculate opacity based on position
      const opacity = Math.cos((position * Math.PI) / 2);

      // Only include items with opacity > 0
      if (opacity > 0) {
        items.push({
          ...item,
          position,
          opacity,
        });
      }
    }

    return items;
  }, [offset, flattenedItems, totalItems, visibleItemCount]);

  const activeGroups = useMemo(() => {
    const groups = new Set(visibleItems.map((item) => item.groupId));
    return groups;
  }, [visibleItems]);

  const pathD = useMemo(() => {
    const midY = containerHeight / 2;
    const controlY = containerHeight / 4;
    const rx = containerWidth / 2 + 360;
    const ry = containerHeight / 2 - 40;
    const centerX = containerWidth / 2;
    const centerY = containerHeight / 2;
    const startAngle = 150 * (Math.PI / 180);
    const endAngle = 30 * (Math.PI / 180);

    const startX = centerX + rx * Math.cos(startAngle);
    const startY = centerY + ry * Math.sin(startAngle);
    const endX = centerX + rx * Math.cos(endAngle);
    const endY = centerY + ry * Math.sin(endAngle);

    return `M${startX},${startY} A${rx},${ry} 0 0 0 ${endX},${endY}`;
  }, [containerWidth, containerHeight]);

  return (
    <div className="mx-auto h-full w-full">
      <div className="pointer-events-none absolute inset-0"></div>
      <div
        className="relative mb-4 flex items-center justify-center overflow-visible rounded-lg bg-gray-100"
        style={{
          width: `${100}%`,
          height: `${(containerWidth / 5) * (IMAGE_HEIGHT / IMAGE_WIDTH)}px`,
        }}
      >
        <svg
          width={"100%"}
          height={containerHeight}
          className="absolute left-0 top-0"
        >
          <path d={pathD} fill="none" stroke="lightgray" />
        </svg>
        <div
          style={{
            width: `${containerWidth}px`,
            height: `${(containerWidth / 5) * (IMAGE_HEIGHT / IMAGE_WIDTH)}px`,
          }}
        >
          <AnimatePresence initial={false}>
            {visibleItems.map((itemObj) => {
              const normalizedPosition = (itemObj.position + 1) / 2; // Convert position to range 0-1
              const distanceFromCenter = Math.abs(normalizedPosition - 0.5);
              const opacity = Math.max(0, 1 - distanceFromCenter * 0.5); // Faster fade-out
              const scale = 0.8 + (1 - distanceFromCenter) * 0.4; // Scale down towards edges

              return (
                <motion.div
                  key={itemObj.id}
                  className="absolute -translate-x-1/2 -translate-y-1/2 transform opacity-0"
                  style={{
                    offsetPath: `path("${pathD}")`,
                    offsetDistance: `${normalizedPosition * 100}%`,
                    opacity: opacity,
                    zIndex: Math.round((1 - distanceFromCenter) * 100),
                    pointerEvents: opacity > 0.1 ? "auto" : "none", // Disable interactions for nearly invisible items
                  }}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: opacity, scale: scale }}
                  exit={{ opacity: 0, scale: 0.8 }}
                  transition={{
                    duration: 0.1,
                    opacity: {
                      duration: 0.07,
                    },
                  }}
                >
                  <Image
                    src={itemObj.item}
                    alt={`${itemObj.projectName} - ${itemObj.title}`}
                    width={containerWidth / 5}
                    height={(containerWidth / 5) * (IMAGE_HEIGHT / IMAGE_WIDTH)}
                    className="rounded-lg object-cover"
                  />
                </motion.div>
              );
            })}
          </AnimatePresence>
        </div>
      </div>
      <div className="flex justify-center space-x-2">
        {itemGroups.map((group) => (
          <div
            key={group.id}
            className={`h-3 w-3 rounded-full ${
              activeGroups.has(group.id) ? "bg-blue-500" : "bg-gray-300"
            }`}
            title={group.name}
          />
        ))}
      </div>
      <div className="mt-2 text-center">
        Active Groups:{" "}
        {Array.from(activeGroups)
          .map((groupId) => {
            const group = itemGroups.find((g) => g.id === groupId);
            return group ? group.name : "";
          })
          .join(", ")}
      </div>
    </div>
  );
};

export default GroupedWheelControlledCarousel;
simplify implementation using framer motion utilities like useTransform. but still should work same.