import { useState, useRef, useEffect } from 'react'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Send, Loader2, Mic, Plus, MessageSquare, Trash2, UserCheck } from 'lucide-react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { aiApi } from '../../lib/api-services'
import { useAuthStore } from '../../store/authStore'
import Button from '../../components/ui/Button'
import { Input, Label, Select } from '../../components/ui/Input'
import Modal from '../../components/ui/Modal'



/** 解析 markdown 内联格式（**bold** 和 `code`）为 TextRun 数组 */


// 通用 AI 历史记录 hook

// 通用历史记录栏组件

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

const QUICK_QUESTIONS = [
  '员工入职没签合同怎么办？',
  '加班费怎么算？',
  '辞退员工需要赔多少？',
  '试用期最长可以约定几个月？',
]

export function ChatTab() {
  const queryClient = useQueryClient()
  const [messages, setMessages] = useState<Message[]>([
    { role: 'assistant', content: '你好！我是你的用工合规顾问，有什么劳动法问题可以直接问我。\n\n你可以问我：\n· 员工入职没签合同怎么办？\n· 加班费怎么算？\n· 辞退员工需要赔多少？' },
  ])
  const [input, setInput] = useState('')
  const [loading, setLoading] = useState(false)
  const [recording, setRecording] = useState(false)
  const [showHistory, setShowHistory] = useState(false)
  const [currentConvId, setCurrentConvId] = useState<string | null>(null)
  const [showConsultModal, setShowConsultModal] = useState(false)
  const [consultForm, setConsultForm] = useState({ type: 'LEGAL' as string, title: '', description: '', contactName: '', contactPhone: '', remark: '' })
  const scrollRef = useRef<HTMLDivElement>(null)
  const recognitionRef = useRef<any>(null)
  const saveTimerRef = useRef<any>(null)

  const { data: conversations } = useQuery<any[]>({
    queryKey: ['ai-conversations'],
    queryFn: async () => {
      return await aiApi.conversations('chat')
    },
  })

  const deleteConvMutation = useMutation({
    mutationFn: (id: string) => aiApi.removeConversation(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['ai-conversations'] }),
  })

  const consultMutation = useMutation({
    mutationFn: async (data: typeof consultForm) => {
      return await aiApi.consult(data)
    },
    onSuccess: () => {
      toast.success('已提交咨询请求，专业律师将尽快与您联系')
      setShowConsultModal(false)
      setConsultForm({ type: 'LEGAL', title: '', description: '', contactName: '', contactPhone: '', remark: '' })
    },
    onError: (err: any) => {
      toast.error(err?.message || '提交失败，请稍后重试')
    },
  })

  useEffect(() => {
    scrollRef.current?.scrollTo(0, scrollRef.current.scrollHeight)
  }, [messages])

  // 自动保存会话（debounce）
  useEffect(() => {
    if (messages.length <= 1) return
    if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
    saveTimerRef.current = setTimeout(async () => {
      const title = `chat:${messages.find(m => m.role === 'user')?.content.slice(0, 30) || '新对话'}`
      if (currentConvId) {
        await aiApi.updateConversation(currentConvId, { messages }).catch(() => {})
      } else {
        const res = await aiApi.createConversation({ title, messages }) as any
        if (res?.id) {
          setCurrentConvId(res.id)
          queryClient.invalidateQueries({ queryKey: ['ai-conversations'] })
        }
      }
    }, 2000)
    return () => { if (saveTimerRef.current) clearTimeout(saveTimerRef.current) }
  }, [messages])

  const loadConversation = async (id: string) => {
    try {
      const res = await aiApi.conversation(id) as any
      if (res?.messages) {
        setMessages(res.messages)
        setCurrentConvId(id)
        setShowHistory(false)
      }
    } catch {}
  }

  const newConversation = () => {
    setMessages([{ role: 'assistant', content: '你好！我是你的用工合规顾问，有什么劳动法问题可以直接问我。\n\n你可以问我：\n· 员工入职没签合同怎么办？\n· 加班费怎么算？\n· 辞退员工需要赔多少？' }])
    setCurrentConvId(null)
    setShowHistory(false)
  }

  const toggleVoice = () => {
    const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition
    if (!SpeechRecognition) {
      toast.error('当前浏览器不支持语音输入，请使用 Chrome 或 Edge')
      return
    }
    if (recording) {
      recognitionRef.current?.stop()
      setRecording(false)
      return
    }
    const recognition = new SpeechRecognition()
    recognition.lang = 'zh-CN'
    recognition.continuous = false
    recognition.interimResults = false
    recognition.onresult = (event: any) => {
      const transcript = event.results[0]?.[0]?.transcript || ''
      setInput((prev) => prev + transcript)
    }
    recognition.onerror = () => setRecording(false)
    recognition.onend = () => setRecording(false)
    recognition.start()
    recognitionRef.current = recognition
    setRecording(true)
  }

  const send = async (text?: string) => {
    const content = text || input.trim()
    if (!content || loading) return

    const newMessages = [...messages, { role: 'user' as const, content }]
    setMessages([...newMessages, { role: 'assistant', content: '' }])
    setInput('')
    setLoading(true)

    try {
      const token = useAuthStore.getState().accessToken
      const controller = new AbortController()
      const timeoutId = setTimeout(() => controller.abort(), 60 * 1000)
      const chatUrl = import.meta.env.DEV ? 'http://localhost:3000/api/v1/ai/chat-stream' : '/api/v1/ai/chat-stream'
      const response = await fetch(chatUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({ messages: newMessages }),
        signal: controller.signal,
      })
      clearTimeout(timeoutId)

      if (!response.ok) {
        const errData = await response.json().catch(() => null)
        throw new Error(errData?.error?.message || '请求失败')
      }

      const reader = response.body?.getReader()
      const decoder = new TextDecoder()
      let accumulated = ''
      let buffer = ''
      let rafId: number | null = null
      let pendingFlush = false

      // 用 RAF 批量刷新，避免每个 token 触发一次 React 重渲染
      const flush = () => {
        pendingFlush = false
        rafId = null
        setMessages([...newMessages, { role: 'assistant', content: accumulated }])
      }
      const scheduleFlush = () => {
        if (!pendingFlush) {
          pendingFlush = true
          rafId = requestAnimationFrame(flush)
        }
      }

      if (reader) {
        while (true) {
          const { done, value } = await reader.read()
          if (done) break
          buffer += decoder.decode(value, { stream: true })
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6).trim()
              if (data === '[DONE]') continue
              try {
                const parsed = JSON.parse(data)
                if (parsed.delta) {
                  accumulated += parsed.delta
                  scheduleFlush()
                }
                if (parsed.error) {
                  throw new Error(parsed.error)
                }
              } catch (parseErr: any) {
                // 只有业务错误（有 message 且不是 SyntaxError）才抛出
                if (parseErr instanceof SyntaxError) {
                  // JSON 解析失败，可能是 SSE 分块截断，跳过等下一块
                  continue
                }
                throw parseErr
              }
            }
          }
        }
        // 确保最后一批内容被刷新
        if (rafId) cancelAnimationFrame(rafId)
        if (accumulated) {
          setMessages([...newMessages, { role: 'assistant', content: accumulated }])
        }
      }
      if (!accumulated) {
        setMessages([...newMessages, { role: 'assistant', content: '（无回复内容）' }])
      }
    } catch (err: any) {
      const isTimeout = err.name === 'AbortError'
      setMessages([...newMessages, { role: 'assistant', content: isTimeout ? '请求超时，AI 服务响应时间过长，请稍后重试或简化问题。' : `抱歉，出错了：${err.message || '请稍后重试'}` }])
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex flex-col" style={{ height: 'calc(100vh - 250px)', minHeight: '400px' }}>
      {/* 顶部操作栏 */}
      <div className="flex items-center gap-2 pb-2 border-b">
        <Button size="sm" variant="secondary" onClick={newConversation}><Plus className="w-4 h-4 mr-1" />新对话</Button>
        <Button size="sm" variant="secondary" onClick={() => setShowHistory(!showHistory)}><MessageSquare className="w-4 h-4 mr-1" />历史会话</Button>
        <Button size="sm" variant="secondary" onClick={() => setShowConsultModal(true)}><UserCheck className="w-4 h-4 mr-1" />联系专业律师</Button>
        {conversations && conversations.length > 0 && (
          <span className="text-xs text-gray-400">{conversations.length} 条历史</span>
        )}
      </div>

      {/* 历史会话列表 */}
      {showHistory && (
        <div className="border-b pb-2 max-h-40 overflow-y-auto">
          {conversations && conversations.length > 0 ? conversations.map((c: any) => (
            <div key={c.id} className="flex items-center justify-between px-2 py-1.5 hover:bg-gray-50 rounded cursor-pointer text-xs">
              <span className="flex-1 truncate" onClick={() => loadConversation(c.id)}>{c.title.replace(/^chat:/, '')}</span>
              <span className="text-gray-400 ml-2">{new Date(c.updatedAt).toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })}</span>
              <button onClick={(e) => { e.stopPropagation(); deleteConvMutation.mutate(c.id) }} className="ml-2 text-gray-400 hover:text-danger"><Trash2 className="w-3 h-3" /></button>
            </div>
          )) : <div className="text-xs text-gray-400 py-2 text-center">暂无历史会话</div>}
        </div>
      )}

      <div ref={scrollRef} className="flex-1 overflow-y-auto space-y-4 pb-4">
        {messages.map((msg, i) => (
          <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
            <div className={`max-w-[85%] px-4 py-3 rounded-lg text-sm leading-relaxed ${
              msg.role === 'user' ? 'bg-primary text-white whitespace-pre-wrap' : 'bg-white border border-gray-200 text-gray-800 shadow-sm'
            }`}>
              {msg.role === 'assistant' ? (
                msg.content ? (
                  <div className="prose prose-sm max-w-none
                    prose-headings:text-gray-900 prose-headings:font-semibold
                    prose-h1:text-base prose-h1:mt-4 prose-h1:mb-2
                    prose-h2:text-sm prose-h2:mt-3 prose-h2:mb-2
                    prose-h3:text-sm prose-h3:mt-2 prose-h3:mb-1
                    prose-p:my-2 prose-p:leading-relaxed
                    prose-li:my-0.5 prose-li:leading-relaxed
                    prose-ul:my-2 prose-ol:my-2
                    prose-code:text-pink-600 prose-code:bg-gray-100 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:before:content-none prose-code:after:content-none
                    prose-pre:bg-gray-900 prose-pre:text-gray-100 prose-pre:rounded-lg prose-pre:p-3 prose-pre:my-3
                    prose-blockquote:border-l-primary prose-blockquote:bg-primary/5 prose-blockquote:py-1 prose-blockquote:px-3 prose-blockquote:rounded-r prose-blockquote:not-italic
                    prose-table:text-xs prose-table:border-collapse
                    prose-th:bg-gray-50 prose-th:px-3 prose-th:py-1.5 prose-th:font-semibold prose-th:border prose-th:border-gray-200
                    prose-td:px-3 prose-td:py-1.5 prose-td:border prose-td:border-gray-200
                    prose-a:text-primary prose-a:no-underline hover:prose-a:underline
                    prose-strong:text-gray-900
                    prose-hr:border-gray-200 prose-hr:my-4
                  ">
                    <ReactMarkdown remarkPlugins={[remarkGfm]}>{msg.content}</ReactMarkdown>
                  </div>
                ) : loading && i === messages.length - 1 ? (
                  <span className="inline-flex items-center gap-1.5 text-gray-500">
                    <Loader2 className="w-3.5 h-3.5 animate-spin" />
                    思考中...
                  </span>
                ) : null
              ) : (
                msg.content
              )}
            </div>
          </div>
        ))}
      </div>

      {/* 快捷问题 */}
      {messages.length <= 1 && (
        <div className="flex flex-wrap gap-2 pb-3">
          {QUICK_QUESTIONS.map((q) => (
            <button
              key={q}
              onClick={() => send(q)}
              className="px-3 py-1.5 text-xs rounded-full border border-gray-300 text-gray-600 hover:bg-gray-50"
            >
              {q}
            </button>
          ))}
        </div>
      )}

      {/* 输入框 */}
      <div className="flex gap-2 pt-2 border-t">
        <Input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && send()}
          placeholder="输入问题..."
          disabled={loading}
        />
        <Button variant="secondary" onClick={toggleVoice} disabled={loading} className={recording ? 'text-danger' : ''}>
          <Mic className="w-4 h-4" />
        </Button>
        <Button onClick={() => send()} disabled={loading || !input.trim()}>
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
        </Button>
      </div>

      {/* 转人工咨询 Modal */}
      {showConsultModal && (
        <Modal open={true} title="联系专业律师" onClose={() => setShowConsultModal(false)}>
          <div className="space-y-3">
            <div className="rounded-md bg-blue-50 border border-blue-200 p-3 text-xs text-blue-700">
              <p className="font-medium mb-1">服务说明</p>
              <p>· <strong>法律咨询</strong>：专业律师在线解答劳动法问题</p>
              <p>· <strong>仲裁代理</strong>：律师代理劳动仲裁案件（付费服务）</p>
              <p>· <strong>出庭服务</strong>：律师代理法院诉讼（付费服务）</p>
              <p className="mt-1">提交后律师将在 24 小时内与您联系。</p>
            </div>
            <div>
              <Label>服务类型</Label>
              <Select value={consultForm.type} onChange={(e) => setConsultForm({ ...consultForm, type: e.target.value })}>
                <option value="LEGAL">法律咨询</option>
                <option value="ARBITRATION">仲裁代理（付费）</option>
                <option value="COURT">出庭服务（付费）</option>
              </Select>
            </div>
            <div>
              <Label>问题标题</Label>
              <Input value={consultForm.title} onChange={(e) => setConsultForm({ ...consultForm, title: e.target.value })} placeholder="简要描述您的问题" />
            </div>
            <div>
              <Label>详细描述</Label>
              <textarea
                className="w-full px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-sm min-h-[80px] resize-y"
                value={consultForm.description}
                onChange={(e) => setConsultForm({ ...consultForm, description: e.target.value })}
                placeholder="请详细描述您遇到的法律问题、涉及的员工情况等"
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>联系人姓名</Label>
                <Input value={consultForm.contactName} onChange={(e) => setConsultForm({ ...consultForm, contactName: e.target.value })} placeholder="您的姓名" />
              </div>
              <div>
                <Label>联系电话</Label>
                <Input value={consultForm.contactPhone} onChange={(e) => setConsultForm({ ...consultForm, contactPhone: e.target.value })} placeholder="手机号码" maxLength={11} />
              </div>
            </div>
            <div>
              <Label>备注（可选）</Label>
              <Input value={consultForm.remark} onChange={(e) => setConsultForm({ ...consultForm, remark: e.target.value })} placeholder="其他需要说明的信息" />
            </div>
            <div className="flex gap-2 justify-end pt-2">
              <Button variant="secondary" size="sm" onClick={() => setShowConsultModal(false)}>取消</Button>
              <Button
                size="sm"
                onClick={() => consultMutation.mutate(consultForm)}
                disabled={consultMutation.isPending || !consultForm.title || !consultForm.description || !consultForm.contactName || !consultForm.contactPhone}
              >
                {consultMutation.isPending ? '提交中...' : '提交咨询'}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

