import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { marked } from 'marked'

// 类型定义
export interface ChatModel {
  id: string
  name: string
  model_type: string
  provider: string
  model: string
  status: string
}

export interface ChatMessage {
  id: number
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  isStreaming?: boolean
}

export interface Agent {
  id: number
  name: string
  avatar: string
  description: string
  accentColor: string
  gradient: string
  status: 'online' | 'offline'
}

export interface ChatSession {
  id: number
  title: string
  agentId: number
  lastMessage: string
  timestamp: Date
}

export interface GroupChat {
  id: number
  name: string
  members: string[]
  lastMessage: string
  timestamp: Date
}

// 配置 marked
marked.setOptions({
  breaks: true,
  gfm: true
})

// 预处理内容：修复一些常见的 Markdown 问题
const preprocessContent = (content: string): string => {
  if (!content) return ''

  // 1. 标题：# 标题 -> # 标题（确保 # 后有空格）
  content = content.replace(/(^|\n)(#{1,6})([^\s#\n])/g, '$1$2 $3')

  // 2. 无序列表：-项目 -> - 项目
  content = content.replace(/(\n)(\s*)([-*+])(\S)/g, '$1$2$3 $4')

  // 3. 有序列表：1.项目 -> 1. 项目
  content = content.replace(/(\n)(\s*)(\d+\.)(\S)/g, '$1$2$3 $4')

  // 4. 引用：>引用 -> > 引用
  content = content.replace(/(\n)(>+)([^\s>\n])/g, '$1$2 $3')

  // 5. 修复 ##1. 这种情况（连续处理）
  content = content.replace(/(#{1,6})(\d+\.)/g, '$1 $2')

  return content
}

// 渲染 Markdown
export const renderMarkdown = (content: string): string => {
  if (!content) return ''
  try {
    const processed = preprocessContent(content)
    return marked.parse(processed) as string
  } catch (e) {
    console.error('Markdown parse error:', e)
    return content
  }
}

// 根据 provider 获取图标
export const getModelIcon = (provider: string) => {
  const icons: Record<string, string> = {
    'OpenAI': '🤖',
    'Claude': '🧠',
    'Google': '✨',
    'Gemini': '✨',
    'Ollama': '🦙',
    'DeepSeek': '🔮',
    'Moonshot': '🌙',
    'Kimi': '🌙',
    'Baidu': '🐉',
    '文心一言': '🐉',
    'Aliyun': '☁️',
    'Ali': '☁️',
    '通义千问': '☁️',
    'Azure': '⬛',
    'Anthropic': '🧠',
  }
  return icons[provider] || '💬'
}

// 创建 composable
export function useChat() {
  // 模型相关状态
  const chatModels = ref<ChatModel[]>([])
  const selectedModel = ref<ChatModel | null>(null)
  const modelsLoading = ref(false)
  const showModelDropdown = ref(false)

  // 助手相关状态
  const chatAgents = ref<Agent[]>([
    { id: 1, name: 'Claude', avatar: '🧠', description: 'Anthropic AI', accentColor: '#f97316', gradient: 'from-orange-500/20 to-amber-500/20', status: 'online' },
    { id: 2, name: 'Gemini', avatar: '✨', description: 'Google DeepMind', accentColor: '#8b5cf6', gradient: 'from-violet-500/20 to-purple-500/20', status: 'online' },
    { id: 3, name: 'ChatGPT', avatar: '💬', description: 'OpenAI', accentColor: '#10b981', gradient: 'from-emerald-500/20 to-green-500/20', status: 'offline' },
    { id: 4, name: 'DeepSeek', avatar: '🔮', description: 'DeepSeek AI', accentColor: '#3b82f6', gradient: 'from-blue-500/20 to-cyan-500/20', status: 'online' },
    { id: 5, name: 'Kimi', avatar: '🌙', description: 'Moonshot AI', accentColor: '#ec4899', gradient: 'from-pink-500/20 to-rose-500/20', status: 'online' },
    { id: 6, name: '文心一言', avatar: '🐉', description: 'Baidu', accentColor: '#ef4444', gradient: 'from-red-500/20 to-orange-500/20', status: 'offline' },
    { id: 7, name: '通义千问', avatar: '☁️', description: 'Alibaba', accentColor: '#06b6d4', gradient: 'from-cyan-500/20 to-sky-500/20', status: 'online' },
  ])
  const selectedAgent = ref<Agent | null>(chatAgents.value[0])

  // 消息相关状态
  const messages = ref<ChatMessage[]>([
    { id: 1, role: 'assistant', content: '你好！我是 Claude，你的 AI 助手。有什么我可以帮助你的吗？', timestamp: new Date() },
  ])

  // 历史对话
  const chatSessions = ref<ChatSession[]>([
    { id: 1, title: '关于 Python 学习的讨论', agentId: 1, lastMessage: '谢谢你！', timestamp: new Date(Date.now() - 3600000) },
    { id: 2, title: '代码调试帮助', agentId: 1, lastMessage: '让我看看这个问题...', timestamp: new Date(Date.now() - 7200000) },
    { id: 3, title: '数据分析咨询', agentId: 4, lastMessage: 'DeepSeek: 好的', timestamp: new Date(Date.now() - 86400000) },
  ])

  // 群聊
  const groupChats = ref<GroupChat[]>([
    { id: 1, name: 'AI 讨论组', members: ['Claude', 'GPT-4', 'Gemini'], lastMessage: '我们来讨论一下...', timestamp: new Date(Date.now() - 1800000) },
    { id: 2, name: '编程助手', members: ['Claude', 'DeepSeek'], lastMessage: '这段代码有问题吗？', timestamp: new Date(Date.now() - 3600000) },
    { id: 3, name: '创意头脑风暴', members: ['GPT-4', 'Claude', 'Kimi'], lastMessage: '有个新想法...', timestamp: new Date(Date.now() - 7200000) },
  ])

  // 智能体选择弹窗
  const showAgentSelector = ref(false)
  const selectMode = ref<'single' | 'group'>('single')
  const selectedAgents = ref<Agent[]>([])
  const groupChatName = ref('')

  // 输入相关
  const inputMessage = ref('')
  const isLoading = ref(false)

  // 侧边栏
  const sidebarCollapsed = ref(false)

  // 获取模型列表
  const fetchModels = async () => {
    modelsLoading.value = true
    try {
      const response = await fetch(`/model/list`)
      const data = await response.json()
      if (data.list) {
        chatModels.value = data.list.filter((m: ChatModel) => m.model_type === 'chat' && m.status === 'active')
        if (chatModels.value.length > 0 && !selectedModel.value) {
          selectedModel.value = chatModels.value[0]
        }
      }
    } catch (error) {
      console.error('Failed to fetch models:', error)
    } finally {
      modelsLoading.value = false
    }
  }

  // 打开智能体选择器
  const openAgentSelector = (mode: 'single' | 'group') => {
    selectMode.value = mode
    selectedAgents.value = []
    groupChatName.value = ''
    showAgentSelector.value = true
  }

  // 切换智能体选择
  const toggleAgentSelection = (agent: Agent) => {
    const index = selectedAgents.value.findIndex(a => a.id === agent.id)
    if (index > -1) {
      selectedAgents.value.splice(index, 1)
    } else {
      selectedAgents.value.push(agent)
    }
  }

  // 确认选择
  const confirmAgentSelection = () => {
    if (selectMode.value === 'single') {
      if (selectedAgents.value.length > 0) {
        selectedAgent.value = selectedAgents.value[0]
        messages.value = [
          { id: 1, role: 'assistant', content: `你好！我是 ${selectedAgent.value.name}，你的 AI 助手。有什么我可以帮助你的吗？`, timestamp: new Date() }
        ]
      }
    } else {
      const name = groupChatName.value.trim() || `群聊 (${selectedAgents.value.length}人)`
      groupChats.value.unshift({
        id: Date.now(),
        name: name,
        members: selectedAgents.value.map(a => a.name),
        lastMessage: 'New group created',
        timestamp: new Date()
      })
    }
    showAgentSelector.value = false
  }

  // 取消选择
  const cancelAgentSelection = () => {
    showAgentSelector.value = false
  }

  // 选择助手
  const selectAgent = (agent: Agent) => {
    selectedAgent.value = agent
    messages.value = [
      { id: 1, role: 'assistant', content: `你好！我是 ${agent.name}。有什么我可以帮助你的吗？`, timestamp: new Date() }
    ]
  }

  // 选择历史对话
  const selectSession = (session: ChatSession) => {
    const agent = chatAgents.value.find(a => a.id === session.agentId)
    if (agent) {
      selectedAgent.value = agent
    }
    messages.value = [
      { id: 1, role: 'assistant', content: `已加载会话：${session.title}`, timestamp: new Date() }
    ]
  }

  // 新建聊天
  const newChat = () => {
    messages.value = [
      { id: 1, role: 'assistant', content: `你好！我是 ${selectedAgent.value?.name || 'Claude'}。有什么我可以帮助你的吗？`, timestamp: new Date() }
    ]
  }

  // 格式化时间
  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 格式化相对时间
  const formatRelativeTime = (date: Date) => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (hours < 1) return '刚刚'
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString('zh-CN')
  }

  // 切换侧边栏
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  // 点击外部关闭下拉框
  const handleClickOutside = (e: MouseEvent) => {
    const target = e.target as HTMLElement
    if (!target.closest('.model-dropdown')) {
      showModelDropdown.value = false
    }
  }

  // 初始化
  onMounted(() => {
    fetchModels()
    document.addEventListener('click', handleClickOutside)
  })

  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside)
  })

  return {
    // 模型
    chatModels,
    selectedModel,
    modelsLoading,
    showModelDropdown,
    fetchModels,
    // 助手
    chatAgents,
    selectedAgent,
    selectAgent,
    // 消息
    messages,
    newChat,
    // 历史对话
    chatSessions,
    selectSession,
    // 群聊
    groupChats,
    // 智能体选择
    showAgentSelector,
    selectMode,
    selectedAgents,
    groupChatName,
    openAgentSelector,
    toggleAgentSelection,
    confirmAgentSelection,
    cancelAgentSelection,
    // 输入
    inputMessage,
    isLoading,
    // 侧边栏
    sidebarCollapsed,
    toggleSidebar,
    // 工具
    formatTime,
    formatRelativeTime,
    getModelIcon,
  }
}
