import { useState, useEffect, useCallback, type RefObject } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';

export const SECTIONS = ['overview', 'timeline', 'tasks', 'notes', 'files'] as const;
export type SectionId = typeof SECTIONS[number];

interface ProjectTabBarProps {
  sectionRefs: Record<SectionId, RefObject<HTMLDivElement | null>>;
  scrollRef: RefObject<HTMLDivElement | null>;
  heroRef: RefObject<HTMLDivElement | null>;
  initialTab?: string;
}

export function ProjectTabBar({ sectionRefs, scrollRef, heroRef, initialTab }: ProjectTabBarProps) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [activeSection, setActiveSection] = useState<SectionId>(
    (SECTIONS.includes(initialTab as SectionId) ? initialTab : 'overview') as SectionId,
  );

  useEffect(() => {
    const root = scrollRef.current;
    if (!root) return;
    const heroH = heroRef.current?.getBoundingClientRect().height ?? 88;
    const tabBarH = 41;
    const visible = new Map<SectionId, IntersectionObserverEntry>();
    const observer = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          const id = e.target.getAttribute('data-section') as SectionId | null;
          if (!id) continue;
          if (e.isIntersecting) visible.set(id, e);
          else visible.delete(id);
        }
        if (visible.size === 0) return;
        let best: SectionId | null = null;
        let bestTop = Infinity;
        for (const [id, e] of visible) {
          const top = e.boundingClientRect.top;
          if (top >= 0 && top < bestTop) { bestTop = top; best = id; }
        }
        if (!best) {
          bestTop = -Infinity;
          for (const [id, e] of visible) {
            const top = e.boundingClientRect.top;
            if (top > bestTop) { bestTop = top; best = id; }
          }
        }
        if (best) setActiveSection(best);
      },
      { root, rootMargin: `-${heroH + tabBarH}px 0px -50% 0px`, threshold: 0 },
    );
    for (const ref of Object.values(sectionRefs)) {
      if (ref.current) observer.observe(ref.current);
    }
    return () => observer.disconnect();
  }, [sectionRefs, scrollRef, heroRef]);

  const scrollToSection = useCallback((id: SectionId) => {
    const el = scrollRef.current;
    if (!el) return;
    if (id === 'overview') {
      el.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      const ref = sectionRefs[id];
      if (!ref?.current) return;
      const heroH = heroRef.current?.getBoundingClientRect().height ?? 88;
      const sectionTop = ref.current.getBoundingClientRect().top;
      const containerTop = el.getBoundingClientRect().top;
      const top = el.scrollTop + sectionTop - containerTop - heroH - 41;
      el.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
    }
    void navigate({
      search: (prev: Record<string, string | undefined>) => ({ ...prev, tab: id }),
      replace: true,
    });
  }, [sectionRefs, scrollRef, heroRef, navigate]);

  const TAB_LABELS: Record<SectionId, string> = {
    overview: t('projects.overview'),
    timeline: t('projects.projectTimeline'),
    tasks: t('projects.tasks'),
    notes: t('projects.notes'),
    files: t('projects.folder.title'),
  };

  return (
    <nav
      className="sticky z-20 backdrop-blur-md border-b border-border/40"
      style={{ top: 'var(--hero-h)' }}
    >
      <div className="mx-auto max-w-6xl px-8 flex gap-0">
        {SECTIONS.map((id) => (
          <button
            key={id}
            type="button"
            onClick={() => scrollToSection(id)}
            className={cn(
              'relative px-4 py-2.5 text-sm font-medium transition-colors',
              'border-b-2 -mb-px',
              activeSection === id
                ? 'border-foreground text-foreground'
                : 'border-transparent text-muted-foreground hover:text-foreground',
            )}
          >
            {TAB_LABELS[id]}
          </button>
        ))}
      </div>
    </nav>
  );
}
