import { useState, useRef, useCallback, useEffect } from 'react'
import type { CalcDocument } from '../hooks/useDocumentStore.ts'
import '../styles/tab-bar.css'

interface TabBarProps {
  tabs: CalcDocument[]
  activeTabId: string
  onTabClick: (id: string) => void
  onTabClose: (id: string) => void
  onTabRename: (id: string, title: string) => void
  onNewTab: () => void
  modifiedIds?: Set<string>
}

export function TabBar({
  tabs,
  activeTabId,
  onTabClick,
  onTabClose,
  onTabRename,
  onNewTab,
  modifiedIds,
}: TabBarProps) {
  const scrollRef = useRef<HTMLDivElement>(null)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editValue, setEditValue] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)

  // Focus input when editing starts
  useEffect(() => {
    if (editingId && inputRef.current) {
      inputRef.current.focus()
      inputRef.current.select()
    }
  }, [editingId])

  // Scroll active tab into view
  useEffect(() => {
    if (!scrollRef.current) return
    const activeEl = scrollRef.current.querySelector('.tab-item.active')
    activeEl?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
  }, [activeTabId])

  const startRename = useCallback((id: string, currentTitle: string) => {
    setEditingId(id)
    setEditValue(currentTitle)
  }, [])

  const commitRename = useCallback(() => {
    if (editingId) {
      onTabRename(editingId, editValue)
      setEditingId(null)
    }
  }, [editingId, editValue, onTabRename])

  const cancelRename = useCallback(() => {
    setEditingId(null)
  }, [])

  const handleMiddleClick = useCallback((e: React.MouseEvent, id: string) => {
    if (e.button === 1) {
      e.preventDefault()
      onTabClose(id)
    }
  }, [onTabClose])

  // Horizontal scroll with mouse wheel
  const handleWheel = useCallback((e: React.WheelEvent) => {
    if (scrollRef.current && e.deltaY !== 0) {
      scrollRef.current.scrollLeft += e.deltaY
    }
  }, [])

  return (
    <div className="tab-bar">
      <div className="tab-bar-scroll" ref={scrollRef} onWheel={handleWheel}>
        {tabs.map(tab => (
          <div
            key={tab.id}
            className={`tab-item ${tab.id === activeTabId ? 'active' : ''}`}
            onClick={() => onTabClick(tab.id)}
            onMouseDown={(e) => handleMiddleClick(e, tab.id)}
            onDoubleClick={() => startRename(tab.id, tab.title)}
            title={tab.title}
          >
            {modifiedIds?.has(tab.id) && (
              <span className="tab-modified-dot" />
            )}

            {editingId === tab.id ? (
              <input
                ref={inputRef}
                className="tab-rename-input"
                value={editValue}
                onChange={e => setEditValue(e.target.value)}
                onBlur={commitRename}
                onKeyDown={e => {
                  if (e.key === 'Enter') commitRename()
                  if (e.key === 'Escape') cancelRename()
                }}
                onClick={e => e.stopPropagation()}
              />
            ) : (
              <span className="tab-label">{tab.title}</span>
            )}

            <button
              className="tab-close"
              onClick={e => {
                e.stopPropagation()
                onTabClose(tab.id)
              }}
              aria-label={`Close ${tab.title}`}
            >
              ×
            </button>
          </div>
        ))}
      </div>
      <button
        className="tab-new"
        onClick={onNewTab}
        aria-label="New document"
        title="New document (Ctrl+N)"
      >
        +
      </button>
    </div>
  )
}
