'use client'

import { useCallback, useEffect, useRef, useState } from 'react'

export interface ToolbarAction {
  label: string
  key: string
  group: 'session' | 'ai'
  confirm?: string // confirmation message, if set will prompt before executing
}

const TOOLBAR_ACTIONS: ToolbarAction[] = [
  { label: '新对话', key: 'new_conversation', group: 'session', confirm: '确定要开始新对话吗？系统会创建一个新的会话，并保留当前会话。' },
  { label: '系统状态', key: 'system_status', group: 'session' },
  { label: '查看上下文', key: 'context', group: 'ai' },
  { label: '清空上下文', key: 'clear_context', group: 'ai', confirm: '确定要清空上下文吗？这将清空消息并重置 AI 上下文。' },
  { label: '总结对话', key: 'summary', group: 'ai' },
  { label: '查看计划', key: 'plan', group: 'ai' },
  { label: '工具列表', key: 'tools', group: 'ai' },
]

interface ChatToolbarProps {
  onAction: (key: string) => void
  disabled?: boolean
}

export function ChatToolbar({
  onAction,
  disabled,
}: ChatToolbarProps) {
  const [open, setOpen] = useState(false)
  const menuRef = useRef<HTMLDivElement>(null)

  const handleToggle = useCallback(() => {
    setOpen(prev => !prev)
  }, [])

  const handleAction = useCallback(
    (action: ToolbarAction) => {
      if (action.confirm && !window.confirm(action.confirm)) return
      setOpen(false)
      onAction(action.key)
    },
    [onAction],
  )

  // Close on click outside
  useEffect(() => {
    if (!open) return
    const handler = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  const sessionActions = TOOLBAR_ACTIONS.filter(a => a.group === 'session')
  const aiActions = TOOLBAR_ACTIONS.filter(a => a.group === 'ai')

  return (
    <div className="relative" ref={menuRef}>
      <button
        type="button"
        onClick={handleToggle}
        className="rounded-md p-1.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700 transition-colors"
        aria-label="工具菜单"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 20 20"
          fill="currentColor"
          className="h-5 w-5"
        >
          <path d="M3 10a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zM8.5 10a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zM15.5 8.5a1.5 1.5 0 100 3 1.5 1.5 0 000-3z" />
        </svg>
      </button>

      {open && (
        <div className="absolute right-0 top-full z-50 mt-1 w-44 rounded-lg border border-slate-200 bg-white py-1 shadow-lg">
          <div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-slate-400">
            会话管理
          </div>
          {sessionActions.map(action => (
            <button
              key={action.key}
              type="button"
              onClick={() => handleAction(action)}
              className="block w-full px-3 py-1.5 text-left text-sm text-slate-700 hover:bg-slate-50 transition-colors"
            >
              {action.label}
            </button>
          ))}

          <div className="my-1 border-t border-slate-100" />

          <div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-slate-400">
            AI 命令
          </div>
          {aiActions.map(action => (
            <button
              key={action.key}
              type="button"
              onClick={() => handleAction(action)}
              disabled={disabled}
              className="block w-full px-3 py-1.5 text-left text-sm text-slate-700 hover:bg-slate-50 transition-colors disabled:cursor-not-allowed disabled:text-slate-300"
            >
              {action.label}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
