import { useState } from 'react';
import { Code, History, MessageSquare, X } from 'lucide-react';
import type { Chat, WorkspacePane } from '@/api/types';
import { StatusDot } from '@/components/StatusDot';
import { PaneHeaderActions } from '@/components/PaneHeaderActions';
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
} from '@/components/ui/context-menu';
import { useLongPress } from '@/hooks/useLongPress';
import { sessionEvents } from '@/hooks/sessionEvents';
import { cn } from '@/lib/utils';

interface Props {
  pane: WorkspacePane;
  tabs: Chat[];
  // Host pane kind — 'coder' shows the Code glyph + routes the "+" to a new
  // BooCode tab. Defaults to 'chat' (the BooChat tab bar).
  tabKind?: 'chat' | 'coder';
  // v2.6.x (Batch 3a): stable session-scoped tab number per chat id. Keyed by
  // chat.id, NEVER by tab position.
  tabNumbers: Record<string, number>;
  onSwitchTab: (tabIdx: number) => void;
  onRemoveTab: (chatId: string) => void;
  onCloseOthers: (chatId: string) => void;
  onCloseToRight: (chatId: string) => void;
  onCloseAll: () => void;
  onNewTab: () => void;
  onSplitPane: (kind: 'chat' | 'terminal' | 'coder') => void;
  onReopenPane?: () => void;
  onShowHistory: () => void;
  onRename: (chatId: string, name: string) => Promise<void>;
  onRemovePane?: () => void;
}

export function ChatTabBar({
  pane,
  tabs,
  tabKind = 'chat',
  tabNumbers,
  onSwitchTab,
  onRemoveTab,
  onCloseOthers,
  onCloseToRight,
  onCloseAll,
  onNewTab,
  onSplitPane,
  onReopenPane,
  onShowHistory,
  onRename,
  onRemovePane,
}: Props) {
  const [renamingId, setRenamingId] = useState<string | null>(null);
  const [renameValue, setRenameValue] = useState('');
  const TabIcon = tabKind === 'coder' ? Code : MessageSquare;
  const newLabel = tabKind === 'coder' ? 'New BooCode' : 'New chat';

  // Long-press: dispatch a synthetic contextmenu event on the tab so the
  // existing Radix ContextMenuTrigger opens at the touch coordinates. Works
  // because asChild composition makes the tab div the trigger element.
  const longPress = useLongPress(({ clientX, clientY, target }) => {
    if (!target || !(target instanceof Element)) return;
    const tab = target.closest('[data-tab-id]') as HTMLElement | null;
    if (!tab) return;
    tab.dispatchEvent(
      new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX, clientY }),
    );
  });

  function startRename(chatId: string, currentName: string | null) {
    setRenamingId(chatId);
    setRenameValue(currentName ?? '');
  }

  async function finishRename() {
    if (renamingId && renameValue.trim()) {
      await onRename(renamingId, renameValue.trim());
    }
    setRenamingId(null);
  }

  return (
    <div className="flex items-center border-b border-border bg-muted/20 h-8 shrink-0 overflow-x-auto max-md:hidden">
      {tabs.map((chat, tabIdx) => {
        const isActive = tabIdx === pane.activeChatIdx;
        const isLast = tabIdx === tabs.length - 1;
        const onlyTab = tabs.length === 1;
        const label = chat.name ?? 'New chat';
        // v2.6.x: stable tab number keyed by chat.id (NOT tab position).
        // Omit gracefully when not yet assigned.
        const tabNumber = tabNumbers[chat.id];
        return (
          <ContextMenu key={chat.id}>
            <ContextMenuTrigger asChild>
              <div
                data-tab-id={chat.id}
                onClick={() => onSwitchTab(tabIdx)}
                onTouchStart={longPress.onTouchStart}
                onTouchMove={longPress.onTouchMove}
                onTouchEnd={longPress.onTouchEnd}
                onTouchCancel={longPress.onTouchCancel}
                style={{ WebkitTouchCallout: 'none' }}
                className={cn(
                  'group flex items-center gap-1.5 px-3 py-1.5 text-xs border-r border-border cursor-default select-none shrink-0',
                  isActive
                    ? 'bg-background text-foreground'
                    : 'bg-muted/30 text-muted-foreground hover:bg-muted/60'
                )}
              >
                <TabIcon size={12} className="shrink-0" />
                <StatusDot chatId={chat.id} />
                {renamingId === chat.id ? (
                  <input
                    autoFocus
                    value={renameValue}
                    onChange={(e) => setRenameValue(e.target.value)}
                    onBlur={() => void finishRename()}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') void finishRename();
                      if (e.key === 'Escape') setRenamingId(null);
                    }}
                    onClick={(e) => e.stopPropagation()}
                    className="bg-transparent border-b border-border text-xs outline-none w-28"
                  />
                ) : (
                  <span
                    className="truncate max-w-[140px]"
                    title={tabNumber !== undefined ? `${tabNumber} · ${label}` : label}
                  >
                    {tabNumber !== undefined ? `${tabNumber} · ${label}` : label}
                  </span>
                )}
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    onRemoveTab(chat.id);
                  }}
                  className="inline-flex items-center justify-center p-0.5 hover:bg-muted rounded opacity-0 group-hover:opacity-60 hover:!opacity-100 shrink-0 max-md:min-h-[44px] max-md:min-w-[44px] max-md:opacity-100"
                  aria-label="Close tab"
                >
                  <X size={10} />
                </button>
              </div>
            </ContextMenuTrigger>
            <ContextMenuContent>
              <ContextMenuItem onSelect={onNewTab}>
                {newLabel}
              </ContextMenuItem>
              <ContextMenuItem
                onSelect={() =>
                  sessionEvents.emit({ type: 'open_chat_in_new_pane', chat_id: chat.id })
                }
              >
                Open in new pane
              </ContextMenuItem>
              <ContextMenuSeparator />
              <ContextMenuItem onSelect={() => startRename(chat.id, chat.name)}>
                Rename
              </ContextMenuItem>
              <ContextMenuSeparator />
              <ContextMenuItem onSelect={() => onRemoveTab(chat.id)}>
                Close
              </ContextMenuItem>
              <ContextMenuItem
                disabled={onlyTab}
                onSelect={() => onCloseOthers(chat.id)}
              >
                Close others
              </ContextMenuItem>
              <ContextMenuItem
                disabled={isLast}
                onSelect={() => onCloseToRight(chat.id)}
              >
                Close to right
              </ContextMenuItem>
              <ContextMenuItem onSelect={() => onCloseAll()}>
                Close all
              </ContextMenuItem>
            </ContextMenuContent>
          </ContextMenu>
        );
      })}

      {tabs.length === 0 && (
        <div className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-muted-foreground">
          <History size={12} className="shrink-0" />
          <span>Session</span>
        </div>
      )}

      <PaneHeaderActions
        className="ml-auto px-1"
        onNewTab={onNewTab}
        tabKind={tabKind}
        onSplitPane={onSplitPane}
        onReopenPane={onReopenPane}
        onShowHistory={onShowHistory}
        onRemovePane={onRemovePane}
        historyActive={pane.kind === 'empty'}
      />
    </div>
  );
}
