import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Menu, X } from 'lucide-react';

export interface TOCSection {
  id: string;
  label: string;
  icon?: React.ReactNode;
}

export interface TableOfContentsProps {
  /** Array of sections to display */
  sections: TOCSection[];
  /** Additional CSS classes */
  className?: string;
  /** Show on mobile (default: false) */
  showOnMobile?: boolean;
  /** Offset for scroll position (for fixed headers) */
  scrollOffset?: number;
}

/**
 * TableOfContents - Sticky navigation for page sections
 *
 * Features:
 * - Highlights current section based on scroll position
 * - Smooth scroll to sections
 * - Collapsible on mobile
 * - Responsive design
 * - Keyboard accessible
 *
 * @example
 * <TableOfContents
 *   sections={[
 *     { id: 'automatic-system', label: 'Sistema Automático' },
 *     { id: 'local-intelligence', label: 'Inteligencia Local' },
 *   ]}
 * />
 */
export const TableOfContents: React.FC<TableOfContentsProps> = ({
  sections,
  className = '',
  showOnMobile = false,
  scrollOffset = 100,
}) => {
  const [activeSection, setActiveSection] = useState<string>('');
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition = window.scrollY + scrollOffset;

      // Find the current section
      for (let i = sections.length - 1; i >= 0; i--) {
        const section = document.getElementById(sections[i].id);
        if (section && section.offsetTop <= scrollPosition) {
          setActiveSection(sections[i].id);
          break;
        }
      }
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // Check initial position

    return () => window.removeEventListener('scroll', handleScroll);
  }, [sections, scrollOffset]);

  const scrollToSection = (sectionId: string) => {
    const element = document.getElementById(sectionId);
    if (element) {
      const top = element.offsetTop - scrollOffset + 20;
      window.scrollTo({ top, behavior: 'smooth' });
      setIsOpen(false); // Close mobile menu after click
    }
  };

  return (
    <>
      {/* Mobile Toggle Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`fixed top-20 right-4 z-50 lg:hidden ${showOnMobile ? '' : 'hidden'} bg-[var(--bg-primary)] border-2 border-[var(--border-primary)] rounded-lg p-2 shadow-lg`}
        aria-label="Toggle table of contents"
      >
        {isOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
      </button>

      {/* Desktop Sidebar */}
      <nav
        className={`hidden lg:block sticky top-24 h-fit max-h-[calc(100vh-120px)] overflow-y-auto ${className}`}
        aria-label="Table of contents"
      >
        <div className="bg-[var(--bg-secondary)] rounded-2xl p-6 border border-[var(--border-primary)]">
          <h2 className="text-sm font-bold text-[var(--text-secondary)] uppercase tracking-wider mb-4">
            Contenido
          </h2>
          <ul className="space-y-2">
            {sections.map((section) => (
              <li key={section.id}>
                <button
                  onClick={() => scrollToSection(section.id)}
                  className={`w-full text-left px-3 py-2 rounded-lg transition-all duration-200 flex items-center gap-2 ${
                    activeSection === section.id
                      ? 'bg-[var(--color-primary)] text-white font-medium'
                      : 'text-[var(--text-secondary)] hover:bg-[var(--bg-primary)] hover:text-[var(--text-primary)]'
                  }`}
                >
                  {section.icon && <span className="flex-shrink-0">{section.icon}</span>}
                  <span className="text-sm">{section.label}</span>
                </button>
              </li>
            ))}
          </ul>
        </div>
      </nav>

      {/* Mobile Drawer */}
      <AnimatePresence>
        {isOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsOpen(false)}
              className="fixed inset-0 bg-black/50 z-40 lg:hidden"
            />

            {/* Drawer */}
            <motion.nav
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ type: 'spring', stiffness: 300, damping: 30 }}
              className="fixed top-0 right-0 bottom-0 w-80 max-w-[80vw] bg-[var(--bg-primary)] shadow-2xl z-50 lg:hidden overflow-y-auto"
              aria-label="Table of contents"
            >
              <div className="p-6">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-lg font-bold text-[var(--text-primary)]">
                    Contenido
                  </h2>
                  <button
                    onClick={() => setIsOpen(false)}
                    className="p-2 hover:bg-[var(--bg-secondary)] rounded-lg transition-colors"
                    aria-label="Cerrar"
                  >
                    <X className="w-6 h-6" />
                  </button>
                </div>

                <ul className="space-y-2">
                  {sections.map((section) => (
                    <li key={section.id}>
                      <button
                        onClick={() => scrollToSection(section.id)}
                        className={`w-full text-left px-4 py-3 rounded-lg transition-all duration-200 flex items-center gap-3 ${
                          activeSection === section.id
                            ? 'bg-[var(--color-primary)] text-white font-medium'
                            : 'text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] hover:text-[var(--text-primary)]'
                        }`}
                      >
                        {section.icon && <span className="flex-shrink-0">{section.icon}</span>}
                        <span>{section.label}</span>
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            </motion.nav>
          </>
        )}
      </AnimatePresence>
    </>
  );
};

export default TableOfContents;
