'use client';

import { useEffect, useState, useRef } from 'react';
import { ProfileSection } from '@/services/profile-sections.service';

interface QuickLink {
  id: string;
  label: string;
}

interface QuickLinksProps {
  scrollContainerRef: React.RefObject<HTMLDivElement | null>;
  sections?: ProfileSection[];
}

// Convert ProfileSection array to QuickLink array
const sectionsToLinks = (sections: ProfileSection[]): QuickLink[] => {
  return sections
    .filter(s => s.isActive && s.fields && s.fields.length > 0)
    .sort((a, b) => (a.effectiveSortOrder || a.sortOrder) - (b.effectiveSortOrder || b.sortOrder))
    .map(section => ({
      id: section.slug,
      label: section.name,
    }));
};

// Fallback links if no sections provided
const defaultLinks: QuickLink[] = [
  { id: 'basic-information', label: 'Basic Information' },
  { id: 'contact-information', label: 'Contact Information' },
  { id: 'professional-info', label: 'Professional Info' },
];

export function QuickLinks({ scrollContainerRef, sections }: QuickLinksProps) {
  const links = sections && sections.length > 0 ? sectionsToLinks(sections) : defaultLinks;
  const [activeLink, setActiveLink] = useState(links[0]?.id || 'basic-information');
  const isClickScrolling = useRef(false);

  useEffect(() => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const handleScroll = () => {
      if (isClickScrolling.current) return;

      const containerRect = container.getBoundingClientRect();
      const containerTop = containerRect.top;

      let currentSection = links[0]?.id || 'basic-information';

      for (const link of links) {
        const element = document.getElementById(link.id);
        if (element) {
          const rect = element.getBoundingClientRect();
          // Check if the section is near the top of the container
          if (rect.top <= containerTop + 100) {
            currentSection = link.id;
          }
        }
      }

      setActiveLink(currentSection);
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [scrollContainerRef, links]);

  const scrollToSection = (id: string) => {
    const container = scrollContainerRef.current;
    const element = document.getElementById(id);

    if (element && container) {
      isClickScrolling.current = true;
      setActiveLink(id);

      const containerRect = container.getBoundingClientRect();
      const elementRect = element.getBoundingClientRect();
      const scrollTop = container.scrollTop + (elementRect.top - containerRect.top) - 20;

      container.scrollTo({
        top: scrollTop,
        behavior: 'smooth'
      });

      // Reset the flag after scroll animation completes
      setTimeout(() => {
        isClickScrolling.current = false;
      }, 500);
    }
  };

  return (
    <div className="bg-white rounded-[20px] p-6">
      <h3 className="text-[16px] font-bold text-[#00293D] font-fractul mb-4">Quick Links</h3>
      <nav className="space-y-1">
        {links.map((link) => (
          <button
            key={link.id}
            onClick={() => scrollToSection(link.id)}
            className={`block w-full text-left px-3 py-2 rounded-lg text-[14px] font-serif transition-colors ${
              activeLink === link.id
                ? 'text-[#E58625] font-semibold bg-[#E58625]/5'
                : 'text-[#00293D] hover:bg-gray-50'
            }`}
          >
            {link.label}
          </button>
        ))}
      </nav>
    </div>
  );
}
