/**
 * 上下文 AI 入口组件 — 嵌入业务页面，传递页面上下文给 AI 助手
 * 支持浮动按钮 + 弹出对话框
 */
import { useState, useRef, useEffect } from 'react'
import { useMutation } from '@tanstack/react-query'
import { Bot, Send, X, Sparkles } from 'lucide-react'
import { aiApi } from '../../lib/api-services'

interface AIContextEntryProps {
  /** 当前页面上下文标识 */
  context: string
  /** 上下文描述（传给后端 AI） */
  contextData?: Record<string, any>
  /** 页面标题 */
  pageTitle: string
}

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
}

/**
 * 上下文 AI 入口 — 浮动按钮 + 弹出式对话框
 * 自动携带当前页面上下文信息
 */
export function AIContextEntry({ context, contextData, pageTitle }: AIContextEntryProps) {
  const [open, setOpen] = useState(false)
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [input, setInput] = useState('')
  const scrollRef = useRef<HTMLDivElement>(null)

  /** 自动滚动到底部 */
  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })
  }, [messages])

  /** AI 问答 */
  const askMutation = useMutation({
    mutationFn: async (question: string) => {
      const res = await aiApi.contextAsk({
        context,
        contextData,
        pageTitle,
        question,
        history: messages.slice(-6),
      }) as any
      return res.data
    },
    onSuccess: (data) => {
      setMessages(prev => [...prev, { role: 'assistant', content: data.answer || data.message || '抱歉，我暂时无法回答这个问题。' }])
    },
    onError: () => {
      setMessages(prev => [...prev, { role: 'assistant', content: 'AI 服务暂时不可用，请稍后再试。' }])
    },
  })

  const handleSend = () => {
    if (!input.trim() || askMutation.isPending) return
    const question = input.trim()
    setMessages(prev => [...prev, { role: 'user', content: question }])
    setInput('')
    askMutation.mutate(question)
  }

  /** 预设问题 */
  const presetQuestions: Record<string, string[]> = {
    roster: ['哪些员工合同即将到期？', '如何批量导入员工？', '试用期员工有哪些风险？'],
    termination: ['离职补偿金如何计算？', '什么情况属于违法解除？', '离职交接清单包含哪些？'],
    social: ['社保基数如何确定？', '公积金缴存比例是多少？', '如何办理月度社保增减员？'],
    money: ['工资条包含哪些项目？', '个税如何计算？', '如何批量发薪？'],
    attendance: ['如何发布月度考勤？', '考勤异常如何处理？'],
  }
  const presets = presetQuestions[context] || []

  return (
    <>
      {/* 浮动按钮 */}
      <button
        onClick={() => setOpen(true)}
        className="fixed bottom-6 right-6 z-40 w-12 h-12 rounded-full bg-primary text-white shadow-lg hover:shadow-xl transition-shadow flex items-center justify-center"
        aria-label="询问 AI"
      >
        <Bot className="w-5 h-5" />
      </button>

      {/* 弹出对话框 */}
      {open && (
        <div className="fixed inset-0 z-50 flex items-end md:items-center justify-center bg-black/20 px-4 pb-4 md:pb-0" onClick={() => setOpen(false)}>
          <div
            className="w-full max-w-md bg-white rounded-xl shadow-2xl border border-gray-200 flex flex-col max-h-[80vh]"
            onClick={(e) => e.stopPropagation()}
          >
            {/* 头部 */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100">
              <div className="flex items-center gap-2">
                <div className="w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center">
                  <Sparkles className="w-4 h-4 text-primary" />
                </div>
                <div>
                  <div className="text-sm font-medium">AI 顾问 · {pageTitle}</div>
                  <div className="text-xs text-gray-400">基于当前页面上下文回答</div>
                </div>
              </div>
              <button onClick={() => setOpen(false)} className="text-gray-400 hover:text-gray-600">
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* 消息列表 */}
            <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-3 space-y-3 min-h-[200px]">
              {messages.length === 0 ? (
                <div className="text-center py-6">
                  <Bot className="w-8 h-8 text-gray-300 mx-auto mb-2" />
                  <div className="text-sm text-gray-400">向 AI 提问关于「{pageTitle}」的问题</div>
                  {presets.length > 0 && (
                    <div className="mt-4 space-y-2">
                      {presets.map((q, i) => (
                        <button
                          key={i}
                          onClick={() => { setInput(q) }}
                          className="block w-full text-left text-xs text-primary bg-primary/5 hover:bg-primary/10 rounded-lg px-3 py-2 transition-colors"
                        >
                          {q}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                messages.map((msg, i) => (
                  <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                    <div className={`max-w-[80%] rounded-lg px-3 py-2 text-sm ${
                      msg.role === 'user'
                        ? 'bg-primary text-white'
                        : 'bg-gray-100 text-gray-700'
                    }`}>
                      {msg.content}
                    </div>
                  </div>
                ))
              )}
              {askMutation.isPending && (
                <div className="flex justify-start">
                  <div className="bg-gray-100 rounded-lg px-3 py-2 text-sm text-gray-400">
                    <span className="inline-flex gap-1">
                      <span className="animate-bounce" style={{ animationDelay: '0ms' }}>·</span>
                      <span className="animate-bounce" style={{ animationDelay: '150ms' }}>·</span>
                      <span className="animate-bounce" style={{ animationDelay: '300ms' }}>·</span>
                    </span>
                  </div>
                </div>
              )}
            </div>

            {/* 输入区 */}
            <div className="px-4 py-3 border-t border-gray-100 flex items-center gap-2">
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') handleSend() }}
                placeholder="输入问题..."
                className="flex-1 text-sm outline-none bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 focus:border-primary focus:ring-2 focus:ring-primary/10 transition-colors"
              />
              <button
                onClick={handleSend}
                disabled={!input.trim() || askMutation.isPending}
                className="w-8 h-8 rounded-lg bg-primary text-white flex items-center justify-center disabled:opacity-40 transition-opacity"
              >
                <Send className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
