import { useState, useRef, useCallback } from 'react'
import { REVIEW_DOC_TYPES } from './shared'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { FileSearch, Loader2, Trash2, Save, History, FileText } from 'lucide-react'
import { aiApi, employeeApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Label, Select } from '../../components/ui/Input'
import Modal from '../../components/ui/Modal'



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


// 通用 AI 历史记录 hook
function useAIHistory(type: 'predict' | 'review' | 'case') {
  const queryClient = useQueryClient()
  const queryKey = [`ai-history-${type}`]

  const { data: history } = useQuery<any[]>({
    queryKey,
    queryFn: async () => {
      return await aiApi.conversations(type)
    },
  })

  const saveMutation = useMutation({
    mutationFn: async ({ title, input, result }: { title: string; input: string; result: string }) => {
      const res = await aiApi.createConversation({
        title: `${type}:${title}`,
        messages: [{ role: 'user', content: input }, { role: 'assistant', content: result }],
      }) as any
      return res
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey }),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => aiApi.removeConversation(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey }),
  })

  const loadHistory = useCallback(async (id: string) => {
    return await aiApi.conversation(id)
  }, [])

  return { history, saveMutation, deleteMutation, loadHistory }
}

// 通用历史记录栏组件
function HistoryBar({ history, onLoad, onDelete }: {
  history: any[]
  onLoad: (id: string) => void
  onDelete: (id: string) => void
}) {
  return (
    <div className="border-b pb-2 max-h-40 overflow-y-auto">
      {history.length > 0 ? history.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={() => onLoad(c.id)}>
            {c.title.replace(/^(predict:|review:|case:)/, '')}
          </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(); onDelete(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>
  )
}

export function ReviewTab() {
  const [contractText, setContractText] = useState('')
  const [result, setResult] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [docType, setDocType] = useState('labor_contract')
  const [fileName, setFileName] = useState('')
  const [showSaveModal, setShowSaveModal] = useState(false)
  const [saveEmployeeId, setSaveEmployeeId] = useState('')
  const [showHistory, setShowHistory] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const { history, saveMutation, deleteMutation, loadHistory } = useAIHistory('review')

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const ext = file.name.toLowerCase().split('.').pop()
    if (ext !== 'docx' && ext !== 'doc') {
      toast.error('仅支持 .docx 格式文件')
      return
    }
    if (file.size > 100 * 1024 * 1024) {
      toast.error('文件大小不能超过 100MB')
      return
    }
    setUploading(true)
    try {
      const formData = new FormData()
      formData.append('file', file)
      const res = await aiApi.reviewUpload(formData) as any
      if (res?.text) {
        setContractText(res.data.text)
        setFileName(file.name)
        toast.success(`已提取文件内容（${res.data.text.length} 字）`)
      }
    } catch (err: any) {
      toast.error(err?.response?.data?.error?.message || '文件上传失败')
    } finally {
      setUploading(false)
      if (fileInputRef.current) fileInputRef.current.value = ''
    }
  }

  const { data: employees } = useQuery<any[]>({
    queryKey: ['employee-list'],
    queryFn: () => employeeApi.list({ status: 'ACTIVE' }),
  })

  const handleReview = async () => {
    if (!contractText.trim()) return
    setLoading(true)
    setResult(null)
    try {
      const res = await aiApi.review(contractText) as any
      setResult(res)
      // 自动保存到历史
      if (res && !res.error) {
        const title = contractText.slice(0, 30).replace(/\n/g, ' ')
        saveMutation.mutate({ title, input: contractText, result: res.data.text || JSON.stringify(res.data) })
      }
    } catch (err: any) {
      setResult({ error: `出错了：${err.response?.data?.error?.message || '请稍后重试'}` })
    } finally {
      setLoading(false)
    }
  }

  const handleLoadHistory = async (id: string) => {
    const data = await loadHistory(id)
    if (data?.messages) {
      const userMsg = data.messages.find((m: any) => m.role === 'user')
      const assistantMsg = data.messages.find((m: any) => m.role === 'assistant')
      if (userMsg) setContractText(userMsg.content)
      if (assistantMsg) {
        try { setResult(JSON.parse(assistantMsg.content)) } catch { setResult({ text: assistantMsg.content }) }
      }
      setShowHistory(false)
    }
  }

  const handleSave = async () => {
    if (!saveEmployeeId || !result) return
    try {
      await aiApi.reviewSave({ employeeId: saveEmployeeId, type: 'REVIEW', input: contractText, result: result.text || JSON.stringify(result) })
      setShowSaveModal(false)
      setSaveEmployeeId('')
      toast.success('已保存到员工档案')
    } catch (err: any) {
      toast.error('保存失败：' + (err.response?.data?.error?.message || '请稍后重试'))
    }
  }

  const levelConfig: Record<string, { color: string; bg: string; label: string }> = {
    RED: { color: 'text-red-600', bg: 'bg-red-50', label: '高风险' },
    YELLOW: { color: 'text-yellow-600', bg: 'bg-yellow-50', label: '中风险' },
    GREEN: { color: 'text-green-600', bg: 'bg-green-50', label: '低风险' },
  }

  return (
    <div className="space-y-4">
      <Card>
        <div className="flex items-center gap-2 mb-4">
          <FileSearch className="w-5 h-5 text-primary" />
          <h2 className="text-sm font-medium">合同审查</h2>
          <Button size="sm" variant="secondary" className="ml-auto" onClick={() => setShowHistory(!showHistory)}><History className="w-4 h-4 mr-1" />历史记录</Button>
        </div>

        {showHistory && (
          <div className="mt-2 mb-3">
            <HistoryBar history={history || []} onLoad={handleLoadHistory} onDelete={(id) => deleteMutation.mutate(id)} />
          </div>
        )}
        <div className="mt-3 space-y-3">
        {/* 文件上传区 */}
        <div>
          <Label>上传文件审查（可选）</Label>
          <div className="flex items-center gap-2">
            <Select value={docType} onChange={(e) => setDocType(e.target.value)} className="w-40">
              {REVIEW_DOC_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
            </Select>
            <input ref={fileInputRef} type="file" accept=".docx,.txt,.pdf" onChange={handleFileUpload} className="hidden" />
            <Button size="sm" variant="secondary" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
              {uploading ? (<><Loader2 className="w-4 h-4 animate-spin mr-1" />提取中...</>) : (<><FileText className="w-4 h-4 mr-1" />上传文件</>)}
            </Button>
            {fileName && <span className="text-xs text-gray-500 truncate max-w-[200px]">{fileName}</span>}
          </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-xs min-h-[200px] resize-y"
          placeholder="粘贴劳动合同文本..."
          value={contractText}
          onChange={(e) => setContractText(e.target.value)}
        />
        <div className="mt-3">
          <Button onClick={handleReview} disabled={loading || !contractText.trim()}>
            {loading ? <><Loader2 className="w-4 h-4 animate-spin mr-1" />审查中...</> : '开始审查'}
          </Button>
        </div>
        </div>
      </Card>

      {result && (
        <Card>
          <div className="flex items-center justify-between mb-3">
            <h3 className="font-medium">审查结果</h3>
            <Button size="sm" variant="secondary" onClick={() => setShowSaveModal(true)}><Save className="w-4 h-4 mr-1" />保存到员工档案</Button>
          </div>
          {result.error ? (
            <div className="text-xs text-danger">{result.error}</div>
          ) : result.structured ? (
            <div className="space-y-3">
              {/* 合规评分 */}
              <div className="flex items-center gap-3">
                <span className="text-xs text-gray-500">合规评分</span>
                <span className={`text-lg font-bold ${result.structured.score >= 80 ? 'text-safe' : result.structured.score >= 60 ? 'text-warning' : 'text-danger'}`}>
                  {result.structured.score}/100
                </span>
              </div>

              {/* 风险项列表 */}
              {result.structured.riskItems.length > 0 && (
                <div className="space-y-2">
                  <h4 className="text-xs font-medium">风险项（{result.structured.riskItems.length}）</h4>
                  {result.structured.riskItems.map((item: any, i: number) => {
                    const cfg = levelConfig[item.level] || levelConfig.YELLOW
                    return (
                      <div key={i} className={`rounded-md p-3 ${cfg.bg}`}>
                        <div className="flex items-center gap-2 mb-1">
                          <span className={`text-xs font-medium ${cfg.color}`}>{cfg.label}</span>
                          <span className="text-xs font-medium">{item.title}</span>
                        </div>
                        <div className="text-xs text-gray-600 mb-1">{item.description}</div>
                        <div className="text-xs text-gray-500">建议：{item.suggestion}</div>
                      </div>
                    )
                  })}
                </div>
              )}

              {/* 总体建议 */}
              {result.structured.summary && (
                <div className="border-t pt-2">
                  <h4 className="text-xs font-medium mb-1">总体建议</h4>
                  <p className="text-xs text-gray-600">{result.structured.summary}</p>
                </div>
              )}

              {/* 原始文本可展开 */}
              <details className="border-t pt-2">
                <summary className="text-xs text-gray-400 cursor-pointer">查看原始文本</summary>
                <div className="text-xs text-gray-700 whitespace-pre-wrap mt-2">{result.text}</div>
              </details>
            </div>
          ) : (
            <div className="text-xs text-gray-700 whitespace-pre-wrap">{result.text || JSON.stringify(result)}</div>
          )}
        </Card>
      )}

      {showSaveModal && (
        <Modal open onClose={() => setShowSaveModal(false)} size="sm">
          <div className="space-y-3">
            <h3 className="font-medium">保存到员工档案</h3>
            <Label>选择员工</Label>
            <Select value={saveEmployeeId} onChange={(e) => setSaveEmployeeId(e.target.value)}>
              <option value="">选择员工</option>
              {(employees || []).map((e: any) => <option key={e.id} value={e.id}>{e.name}（{e.department}）</option>)}
            </Select>
            <div className="flex gap-2 justify-end">
              <Button variant="secondary" size="sm" onClick={() => setShowSaveModal(false)}>取消</Button>
              <Button size="sm" onClick={handleSave} disabled={!saveEmployeeId}>保存</Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}
