"use client"

import { useState, useRef, useEffect, useCallback, memo } from "react"
import { MessageSquare } from "lucide-react"
import { formatTime } from "./timeline-helpers"
import { TimelineSectionCard } from "./timeline-section-card"
import { TimelineChat } from "./timeline-chat"
import {
  ResizablePanelGroup,
  ResizablePanel,
  ResizableHandle,
} from "@/components/ui/resizable"
import type { Layout } from "react-resizable-panels"
import type { TimelineSection } from "./timeline-types"

interface TimelinePageViewProps {
  sections: TimelineSection[]
  totalDuration: number
  functionName?: string | null
  filePath?: string | null
  traceId?: string
}

export const TimelinePageView = memo(function TimelinePageView({
  sections,
  totalDuration,
  functionName,
  filePath,
  traceId,
}: TimelinePageViewProps) {
  const [activeIndex, setActiveIndex] = useState(0)
  const [chatOpen, setChatOpen] = useState(false)
  const sectionRefs = useRef<(HTMLDivElement | null)[]>([])
  const refCallbacks = useRef(new Map<number, (el: HTMLDivElement | null) => void>())
  const scrollContainerRef = useRef<HTMLDivElement>(null)

  const [savedLayout, setSavedLayout] = useState<Layout | undefined>(undefined)

  useEffect(() => {
    try {
      const stored = localStorage.getItem("obs-chat-layout")
      if (stored) setSavedLayout(JSON.parse(stored))
    } catch { /* ignore */ }
  }, [])

  const handleLayoutChanged = useCallback((layout: Layout) => {
    try { localStorage.setItem("obs-chat-layout", JSON.stringify(layout)) } catch { /* ignore */ }
  }, [])

  function getSectionRef(index: number) {
    let cb = refCallbacks.current.get(index)
    if (!cb) {
      cb = (el: HTMLDivElement | null) => { sectionRefs.current[index] = el }
      refCallbacks.current.set(index, cb)
    }
    return cb
  }

  useEffect(() => {
    // When chat is open, the timeline scrolls inside a panel container
    // rather than the viewport, so use that container as the observer root
    const root = chatOpen ? scrollContainerRef.current : null

    const observer = new IntersectionObserver(
      (entries) => {
        let bestIndex = -1
        let bestDistance = Infinity

        for (const entry of entries) {
          if (!entry.isIntersecting) continue

          const index = Number(entry.target.getAttribute("data-section-index"))
          if (isNaN(index)) continue

          const rect = entry.boundingClientRect
          const sectionMiddle = rect.top + rect.height / 2
          const viewportH = root ? root.clientHeight : window.innerHeight
          const rootTop = root ? root.getBoundingClientRect().top : 0
          const distance = Math.abs((sectionMiddle - rootTop) - viewportH * 0.35)

          if (distance < bestDistance) {
            bestDistance = distance
            bestIndex = index
          }
        }

        if (bestIndex >= 0) {
          setActiveIndex(bestIndex)
        }
      },
      {
        root,
        threshold: [0.5],
        rootMargin: "-10% 0px -55% 0px",
      }
    )

    sectionRefs.current.forEach((ref, index) => {
      if (ref) {
        ref.setAttribute("data-section-index", String(index))
        observer.observe(ref)
      }
    })

    return () => observer.disconnect()
  }, [sections.length, chatOpen])

  const toggleChat = useCallback(() => setChatOpen((prev) => !prev), [])
  const closeChat = useCallback(() => setChatOpen(false), [])

  if (sections.length === 0) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-400">
        No timeline data available
      </div>
    )
  }

  const activeSection = sections[activeIndex]
  const shouldExpandContainer =
    activeSection?.content.type === "candidate" ||
    activeSection?.content.type === "refinement"

  const timelineSections = (
    <>
      <div className="sticky top-1/2 -translate-y-1/2 z-20 pointer-events-none h-0">
        <div className="absolute right-4 -top-2">
          <div className="w-4 h-4 rounded-full bg-zinc-400 dark:bg-zinc-500 border-2 border-white dark:border-zinc-900" />
        </div>
      </div>

      {sections.map((section, index) => (
        <div
          key={section.id}
          ref={getSectionRef(index)}
          className="scroll-mt-24"
        >
          <TimelineSectionCard
            section={section}
            isActive={index === activeIndex}
            index={index}
            totalSections={sections.length}
          />
        </div>
      ))}

      <div className="relative">
        <div className="absolute right-6 top-0 h-6 w-px bg-zinc-200 dark:bg-zinc-700" />
        <div className="absolute right-4 top-6 w-4 h-4 rounded-full bg-zinc-300 dark:bg-zinc-600 border-2 border-white dark:border-zinc-900 z-10" />
        <div className="mr-14 py-4 text-right">
          <span className="text-xs text-zinc-500 dark:text-zinc-400">
            End
          </span>
        </div>
      </div>
    </>
  )

  const header = (
    <div className={`${chatOpen ? "flex-shrink-0" : "sticky top-0"} z-30 bg-white dark:bg-zinc-900 border-b border-zinc-200 dark:border-zinc-700`}>
      <div className="max-w-6xl mx-auto px-4 py-3">
        <div className="flex items-center justify-between mb-2">
          <div>
            <h2 className="text-sm font-medium text-zinc-900 dark:text-white">
              Optimization Timeline
            </h2>
            {functionName && (
              <p className="text-xs text-zinc-500 dark:text-zinc-400">
                {functionName}
                {filePath && <span className="ml-1 opacity-60">in {filePath}</span>}
              </p>
            )}
          </div>
          <div className="flex items-center gap-3">
            {traceId && (
              <button
                onClick={toggleChat}
                className={`flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-md transition-colors ${
                  chatOpen
                    ? "bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300"
                    : "text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-700"
                }`}
                title="Chat with this trace"
              >
                <MessageSquare className="h-3.5 w-3.5" />
                <span>Chat</span>
              </button>
            )}
            <span className="text-xs text-zinc-500 dark:text-zinc-400">
              {activeIndex + 1} of {sections.length} {"\u00b7"} {formatTime(totalDuration)}
            </span>
          </div>
        </div>

        <div className="h-1 bg-zinc-200 dark:bg-zinc-700 rounded-full overflow-hidden">
          <div
            className="h-full bg-zinc-400 dark:bg-zinc-500 transition-[width] duration-200"
            style={{ width: `${((activeIndex + 1) / sections.length) * 100}%` }}
          />
        </div>
      </div>
    </div>
  )

  if (chatOpen && traceId) {
    return (
      <div className="flex flex-col h-screen">
        {header}
        <ResizablePanelGroup
          orientation="horizontal"
          defaultLayout={savedLayout}
          onLayoutChanged={handleLayoutChanged}
          className="flex-1 min-h-0"
        >
          <ResizablePanel id="timeline" defaultSize="65%" minSize="30%">
            <div
              ref={scrollContainerRef}
              className={`h-full overflow-y-auto px-4 pb-20 mx-auto ${
                shouldExpandContainer ? "max-w-full" : "max-w-6xl"
              }`}
            >
              {timelineSections}
            </div>
          </ResizablePanel>
          <ResizableHandle withHandle />
          <ResizablePanel id="chat" defaultSize="35%" minSize="20%" maxSize="50%">
            <TimelineChat traceId={traceId} onClose={closeChat} />
          </ResizablePanel>
        </ResizablePanelGroup>
      </div>
    )
  }

  return (
    <div className="relative">
      {header}
      <div
        className={`mx-auto px-4 pb-20 relative mt-6 ${
          shouldExpandContainer ? "max-w-full" : "max-w-6xl"
        }`}
      >
        {timelineSections}
      </div>
    </div>
  )
})
