'use client'
import React, { useState, useEffect, useRef } from "react";
import { getActiveMilestones, type Milestone } from "../../services/milestoneService";

// Define CalendarIcon at the top level
const CalendarIcon = (
  <svg
    width={34}
    height={34}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
    <line x1="16" y1="2" x2="16" y2="6" />
    <line x1="8" y1="2" x2="8" y2="6" />
    <line x1="3" y1="10" x2="21" y2="10" />
  </svg>
);

export default function Process() {
  const [activeStep, setActiveStep] = useState(0);
  const [milestones, setMilestones] = useState<Milestone[]>([]);
  const [loading, setLoading] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const timelineRef = useRef<HTMLDivElement>(null);
  const stepRefs = useRef<HTMLDivElement[]>([]);

  // Fetch milestones from API
  useEffect(() => {
    async function fetchMilestones() {
      try {
        setLoading(true);
        const data = await getActiveMilestones();
        
        // Sort by milestoneDate in descending order (newest first)
        const sortedData = [...data].sort((a, b) => {
          const dateA = new Date(a.milestoneDate || 0).getTime();
          const dateB = new Date(b.milestoneDate || 0).getTime();
          return dateB - dateA; // Descending order (newest first)
        });
        
        setMilestones(sortedData);
      } catch (error) {
        console.error('Failed to fetch milestones:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchMilestones();
  }, []);

  // Transform API data to match the component's step format
  const steps = milestones.map((milestone, index) => ({
    number: (index + 1).toString(),
    title: milestone.title,
    description: milestone.description,
    icon: CalendarIcon,
  }));

  // Initialize step refs array
  useEffect(() => {
    stepRefs.current = stepRefs.current.slice(0, steps.length);
  }, [steps.length]);

  // Calculate extra scroll height based on number of items
  const extraHeight = steps.length > 0 ? Math.max(800, steps.length * 150) : 0;

  useEffect(() => {
    const handleScroll = () => {
      if (!containerRef.current || !timelineRef.current) return;
      
      const container = containerRef.current;
      const timeline = timelineRef.current;
      const rect = container.getBoundingClientRect();
      const windowHeight = window.innerHeight;
      const containerHeight = container.offsetHeight;
      
      // Calculate when to start the scroll effect (when "Milestones" text reaches near top)
      const scrollStartOffset = 100; // Adjust this to control when scrolling starts
      
      if (rect.top <= scrollStartOffset && rect.bottom >= windowHeight) {
        // Section is in the sticky zone
        const scrollableHeight = containerHeight - windowHeight;
        const scrolled = Math.abs(rect.top - scrollStartOffset);
        const progress = Math.max(0, Math.min(1, scrolled / scrollableHeight));
        
        // Scroll the timeline
        const timelineHeight = timeline.scrollHeight - timeline.clientHeight;
        timeline.scrollTop = progress * timelineHeight;
        
        // Calculate which step should be active based on scroll position
        const viewportCenter = timeline.scrollTop + timeline.clientHeight / 3;
        
        let newActiveStep = 0;
        stepRefs.current.forEach((ref, index) => {
          if (ref) {
            const stepTop = ref.offsetTop;
            if (stepTop <= viewportCenter) {
              newActiveStep = index;
            }
          }
        });
        
        setActiveStep(newActiveStep);
      } else if (rect.top > scrollStartOffset) {
        // Before sticky zone
        timeline.scrollTop = 0;
        setActiveStep(0);
      } else {
        // After sticky zone
        const timelineHeight = timeline.scrollHeight - timeline.clientHeight;
        timeline.scrollTop = timelineHeight;
        setActiveStep(steps.length - 1);
      }
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // Initial check
    
    return () => window.removeEventListener('scroll', handleScroll);
  }, [steps.length]);

  // Loading state
  if (loading) {
    return (
      <div className="bg-white py-8 sm:py-12 min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 mb-4" style={{ borderColor: "#012068" }}></div>
          <p className="text-lg" style={{ color: "#012068" }}>Loading milestones...</p>
        </div>
      </div>
    );
  }

  // Empty state
  if (steps.length === 0) {
    return (
      <div className="bg-white py-8 sm:py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-xl mb-4" style={{ color: "#e64838" }}>
            Milestones
          </div>
          <h2 className="text-3xl sm:text-4xl md:text-5xl font-bold leading-tight mb-6" style={{ color: "#012068" }}>
            Our Journey in Trauma Care
          </h2>
          <p className="text-base sm:text-lg leading-relaxed" style={{ color: '#333' }}>
            No milestones available at the moment.
          </p>
        </div>
      </div>
    );
  }

  // For small number of items (1-3), use static layout without sticky scroll
  const isSmallList = steps.length <= 3;

  if (isSmallList) {
    return (
      <div className="bg-white py-8 sm:py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-start">
            {/* Left Column */}
            <div className="flex flex-col justify-start">
              <div>
                <div className="text-xl mb-4" style={{ color: "#e64838" }}>
                  Milestones
                </div>
                <h2
                  className="text-3xl sm:text-4xl md:text-5xl font-bold leading-tight mb-6"
                  style={{ color: "#012068" }}
                >
                  Our Journey in Trauma Care
                </h2>
                <p className="text-base sm:text-lg leading-relaxed" style={{ color: '#333' }}>
                  From the formation of Trauma Services in 2017 to establishing a Level-1 Trauma Facility and comprehensive trauma care programs, we continue to expand our emergency care services with dedication and excellence.
                </p>
              </div>
            </div>

            {/* Right Column - Static Timeline */}
            <div className="relative">
              {steps.map((step, index) => (
                <div
                  key={index}
                  className={`relative group transition-all duration-500 ${
                    index !== 0 ? "mt-10" : ""
                  }`}
                  onMouseEnter={() => setActiveStep(index)}
                  onMouseLeave={() => setActiveStep(-1)}
                >
                  {/* Connecting Line */}
                  {index !== 0 && (
                    <div className="absolute left-6 -top-10 w-0.5 h-10 bg-gray-300 overflow-hidden">
                      <div
                        className="w-full h-full transition-all duration-700"
                        style={{ backgroundColor: "#012068" }}
                      />
                    </div>
                  )}

                  {/* Step Content */}
                  <div className="flex items-start gap-4 sm:gap-6 pl-2">
                    {/* Number Circle */}
                    <div
                      className={`relative z-10 flex-shrink-0 w-12 h-12 rounded-full flex items-center justify-center text-white font-semibold text-lg transition-all duration-500 transform ${
                        activeStep === index ? "scale-110 shadow-lg ring-4" : "scale-100 hover:scale-105"
                      }`}
                      style={{
                        backgroundColor: activeStep === index ? "#012068" : "#333",
                        "--tw-ring-color": activeStep === index ? "#01206833" : "transparent",
                      } as React.CSSProperties}
                    >
                      {step.number}
                    </div>

                    {/* Step Card */}
                    <div
                      className={`flex-1 p-4 sm:p-6 rounded-lg border transition-all duration-500 transform min-h-[180px] ${
                        activeStep === index
                          ? "border-transparent text-white shadow-2xl scale-105 -translate-y-2"
                          : "border-gray-300 hover:shadow-lg hover:-translate-y-1"
                      }`}
                      style={{
                        backgroundColor: activeStep === index ? "#012068" : "#f4f4f4",
                        color: activeStep === index ? "white" : "#333",
                      }}
                    >
                      {/* Icon */}
                      <div
                        className="mb-4 transition-all duration-500"
                        style={{
                          color: activeStep === index ? "white" : "black",
                        }}
                      >
                        {step.icon}
                      </div>

                      {/* Text */}
                      <h3 className="text-lg sm:text-xl font-semibold mb-3 transition-all duration-300 break-words">
                        {step.title}
                      </h3>
                      <p className="text-sm sm:text-base leading-relaxed transition-all duration-500 break-words whitespace-normal">
                        {step.description}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // For larger lists (4+), use sticky scroll behavior
  return (
    <div 
      ref={containerRef}
      className="bg-white relative mb-0" 
      style={{ 
        minHeight: `calc(100vh + ${extraHeight}px)`,
      }}
    >
      <div className="sticky top-0 h-screen flex items-center overflow-hidden">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-start">
            {/* Left Column - Fixed Header */}
            <div className="flex flex-col justify-start lg:sticky lg:top-1/4">
              <div>
                <div className="text-xl mb-4" style={{ color: "#e64838" }}>
                  Milestones
                </div>
                <h2
                  className="text-3xl sm:text-4xl md:text-5xl font-bold leading-tight mb-6"
                  style={{ color: "#012068" }}
                >
                  Our Journey in Trauma Care
                </h2>
                <p className="text-base sm:text-lg leading-relaxed" style={{ color: '#333' }}>
                  From the formation of Trauma Services in 2017 to establishing a Level-1 Trauma Facility and comprehensive trauma care programs, we continue to expand our emergency care services with dedication and excellence.
                </p>
              </div>
            </div>

            {/* Right Column - Auto-scrolling Timeline */}
            <div className="relative h-[70vh] max-h-[600px]">
              <div 
                ref={timelineRef}
                className="h-full overflow-y-auto pr-4 pl-4 [&::-webkit-scrollbar]:hidden pointer-events-none" 
                style={{
                  scrollbarWidth: 'none',
                  msOverflowStyle: 'none'
                }}
              >
                <div className="py-4">
                  {steps.map((step, index) => (
                    <div
                      key={index}
                      ref={(el) => {
                        if (el) {
                          stepRefs.current[index] = el;
                        }
                      }}
                      className={`relative group transition-all duration-500 ${
                        index !== 0 ? "mt-10" : ""
                      }`}
                    >
                      {/* Connecting Line */}
                      {index !== 0 && (
                        <div className="absolute left-6 -top-10 w-0.5 h-10 bg-gray-300 overflow-hidden">
                          <div
                            className={`w-full transition-all duration-700 ease-out origin-top ${
                              activeStep >= index ? "h-full scale-y-100" : "h-0 scale-y-0"
                            }`}
                            style={{ backgroundColor: "#012068" }}
                          />
                        </div>
                      )}

                      {/* Step Content */}
                      <div className="flex items-start gap-4 sm:gap-6">
                        {/* Number Circle */}
                        <div
                          className={`relative z-10 flex-shrink-0 w-12 h-12 rounded-full flex items-center justify-center text-white font-semibold text-lg transition-all duration-500 transform ${
                            activeStep === index
                              ? "scale-110 shadow-lg ring-4"
                              : "scale-100"
                          }`}
                          style={{
                            backgroundColor: activeStep === index ? "#012068" : "#333",
                            "--tw-ring-color": activeStep === index ? "#01206833" : "transparent",
                          } as React.CSSProperties}
                        >
                          {step.number}
                        </div>

                        {/* Step Card */}
                        <div
                          className={`flex-1 p-4 sm:p-6 rounded-lg border transition-all duration-500 transform min-h-[180px] ${
                            activeStep === index
                              ? "border-transparent text-white shadow-2xl scale-105 -translate-y-2"
                              : "border-gray-300"
                          }`}
                          style={{
                            backgroundColor: activeStep === index ? "#012068" : "#f4f4f4",
                            color: activeStep === index ? "white" : "#333",
                          }}
                        >
                          {/* Icon */}
                          <div
                            className="mb-4 transition-all duration-500"
                            style={{
                              color: activeStep === index ? "white" : "black",
                            }}
                          >
                            {step.icon}
                          </div>

                          {/* Text */}
                          <h3 className="text-lg sm:text-xl font-semibold mb-3 transition-all duration-300 break-words">
                            {step.title}
                          </h3>
                          <p className="text-sm sm:text-base leading-relaxed transition-all duration-500 break-words whitespace-normal">
                            {step.description}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}