"use client";
import React, { useEffect, useRef, useState } from "react";
import {
  useMotionValueEvent,
  useScroll,
  useTransform,
  motion,
} from "motion/react";
import { cn } from "../shared/utils";
import { BaseComponentProps } from "../shared/types";

export interface TimelineEntry {
  title: string;
  content: React.ReactNode;
  date?: string;
  icon?: React.ReactNode;
}

export interface TimelineProps extends BaseComponentProps {
  data: TimelineEntry[];
  variant?: 'default' | 'gradient' | 'minimal';
  size?: 'sm' | 'md' | 'lg';
  title?: string;
  subtitle?: string;
  showProgress?: boolean;
  progressColor?: 'purple' | 'blue' | 'green' | 'custom';
  customProgressColor?: string;
  stickyOffset?: number;
}

export const Timeline: React.FC<TimelineProps> = ({
  data,
  variant = 'default',
  size = 'md',
  title = "Timeline",
  subtitle,
  showProgress = true,
  progressColor = 'purple',
  customProgressColor,
  stickyOffset = 40,
  className,
  ...props
}) => {
  const ref = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [height, setHeight] = useState(0);

  useEffect(() => {
    if (ref.current) {
      const rect = ref.current.getBoundingClientRect();
      setHeight(rect.height);
    }
  }, [ref]);

  const { scrollYProgress } = useScroll({
    target: containerRef,
    offset: ["start 10%", "end 50%"],
  });

  const heightTransform = useTransform(scrollYProgress, [0, 1], [0, height]);
  const opacityTransform = useTransform(scrollYProgress, [0, 0.1], [0, 1]);

  const sizeClasses = {
    sm: {
      container: 'py-12 px-4 md:px-6 lg:px-8',
      title: 'text-lg md:text-2xl mb-3',
      subtitle: 'text-sm md:text-base max-w-sm',
      item: 'pt-6 md:pt-20 md:gap-6',
      sticky: 'top-20 max-w-xs',
      titleText: 'text-lg md:pl-16 md:text-3xl',
      mobileTitle: 'text-xl mb-3',
      content: 'pl-16 pr-4 md:pl-4',
      line: 'left-6 md:left-6',
      dot: 'h-8 w-8',
      innerDot: 'h-3 w-3'
    },
    md: {
      container: 'py-16 px-4 md:px-8 lg:px-10',
      title: 'text-lg md:text-3xl mb-4',
      subtitle: 'text-sm md:text-base max-w-sm',
      item: 'pt-8 md:pt-32 md:gap-8',
      sticky: 'top-32 max-w-xs lg:max-w-sm',
      titleText: 'text-xl md:pl-20 md:text-4xl',
      mobileTitle: 'text-2xl mb-4',
      content: 'pl-20 pr-4 md:pl-4',
      line: 'left-8 md:left-8',
      dot: 'h-10 w-10',
      innerDot: 'h-4 w-4'
    },
    lg: {
      container: 'py-20 px-4 md:px-8 lg:px-10',
      title: 'text-lg md:text-4xl mb-4',
      subtitle: 'text-sm md:text-base max-w-sm',
      item: 'pt-10 md:pt-40 md:gap-10',
      sticky: 'top-40 max-w-xs lg:max-w-sm',
      titleText: 'text-xl md:pl-20 md:text-5xl',
      mobileTitle: 'text-2xl mb-4',
      content: 'pl-20 pr-4 md:pl-4',
      line: 'left-8 md:left-8',
      dot: 'h-10 w-10',
      innerDot: 'h-4 w-4'
    }
  };

  const variantClasses = {
    default: 'bg-white dark:bg-neutral-950',
    gradient: 'bg-gradient-to-br from-white via-gray-50 to-white dark:from-neutral-950 dark:via-neutral-900 dark:to-neutral-950',
    minimal: 'bg-transparent'
  };

  const progressColors = {
    purple: 'from-purple-500 via-blue-500 to-transparent',
    blue: 'from-blue-500 via-cyan-500 to-transparent',
    green: 'from-green-500 via-emerald-500 to-transparent',
    custom: customProgressColor ? `from-[${customProgressColor}] via-[${customProgressColor}]/80 to-transparent` : 'from-purple-500 via-blue-500 to-transparent'
  };

  const currentSize = sizeClasses[size];

  return (
    <div
      className={cn(
        "w-full font-sans",
        variantClasses[variant],
        className
      )}
      ref={containerRef}
      {...props}
    >
      <div className={cn("max-w-7xl mx-auto", currentSize.container)}>
        <h2 className={cn(
          "text-black dark:text-white max-w-4xl font-bold",
          currentSize.title
        )}>
          {title}
        </h2>
        {subtitle && (
          <p className={cn(
            "text-neutral-700 dark:text-neutral-300 max-w-sm",
            currentSize.subtitle
          )}>
            {subtitle}
          </p>
        )}
      </div>

      <div ref={ref} className="relative max-w-7xl mx-auto pb-20">
        {data.map((item, index) => (
          <div
            key={index}
            className={cn(
              "flex justify-start",
              currentSize.item
            )}
          >
            <div 
              className={cn(
                "sticky flex flex-col md:flex-row z-40 items-center self-start md:w-full",
                currentSize.sticky
              )}
              style={{ top: `${stickyOffset}px` }}
            >
              <div className={cn(
                "absolute left-3 md:left-3 rounded-full bg-white dark:bg-black flex items-center justify-center border border-neutral-200 dark:border-neutral-800",
                currentSize.dot
              )}>
                {item.icon ? (
                  <div className="text-neutral-600 dark:text-neutral-400">
                    {item.icon}
                  </div>
                ) : (
                  <div className={cn(
                    "rounded-full bg-neutral-200 dark:bg-neutral-800 border border-neutral-300 dark:border-neutral-700",
                    currentSize.innerDot
                  )} />
                )}
              </div>
              <h3 className={cn(
                "hidden md:block font-bold text-neutral-500 dark:text-neutral-500",
                currentSize.titleText
              )}>
                {item.title}
              </h3>
              {item.date && (
                <span className="hidden md:block text-sm text-neutral-400 dark:text-neutral-600 mt-2 md:pl-20">
                  {item.date}
                </span>
              )}
            </div>

            <div className={cn(
              "relative w-full",
              currentSize.content
            )}>
              <h3 className={cn(
                "md:hidden block font-bold text-neutral-500 dark:text-neutral-500",
                currentSize.mobileTitle
              )}>
                {item.title}
              </h3>
              {item.date && (
                <span className="md:hidden block text-sm text-neutral-400 dark:text-neutral-600 mb-3">
                  {item.date}
                </span>
              )}
              {item.content}
            </div>
          </div>
        ))}
        
        {showProgress && (
          <div
            style={{
              height: height + "px",
            }}
            className={cn(
              "absolute top-0 overflow-hidden w-[2px] bg-[linear-gradient(to_bottom,var(--tw-gradient-stops))] from-transparent from-[0%] via-neutral-200 dark:via-neutral-700 to-transparent to-[99%] [mask-image:linear-gradient(to_bottom,transparent_0%,black_10%,black_90%,transparent_100%)]",
              currentSize.line
            )}
          >
            <motion.div
              style={{
                height: heightTransform,
                opacity: opacityTransform,
              }}
              className={cn(
                "absolute inset-x-0 top-0 w-[2px] bg-gradient-to-t rounded-full",
                progressColors[progressColor]
              )}
            />
          </div>
        )}
      </div>
    </div>
  );
};
