import { computed, type Component } from 'vue'
import type { IChatMessage } from '@/api/types'
import UserBubble from '@/components/chat/messages/UserBubble.vue'
import AssistantText from '@/components/chat/messages/AssistantText.vue'
import TeamPlanCard from '@/components/chat/messages/TeamPlanCard.vue'
import BoardBannerCard from '@/components/chat/messages/BoardBannerCard.vue'
import BoardRoundCard from '@/components/chat/messages/BoardRoundCard.vue'
import BoardConclusionCard from '@/components/chat/messages/BoardConclusionCard.vue'
import DebateBannerCard from '@/components/chat/messages/DebateBannerCard.vue'
import DebateArgumentCard from '@/components/chat/messages/DebateArgumentCard.vue'
import DebateSummaryCard from '@/components/chat/messages/DebateSummaryCard.vue'
import DebateConclusionCard from '@/components/chat/messages/DebateConclusionCard.vue'
import CollaborationGraphCard from '@/components/chat/messages/CollaborationGraphCard.vue'
import ReviewResultCard from '@/components/chat/messages/ReviewResultCard.vue'
import RiskFlagCard from '@/components/chat/messages/RiskFlagCard.vue'
import ErrorCard from '@/components/chat/messages/ErrorCard.vue'

export type MessageViewType =
  | 'user'
  | 'assistant'
  | 'team_plan'
  | 'board_banner'
  | 'board_speech'
  | 'board_summary'
  | 'board_conclusion'
  | 'debate_started'
  | 'debate_argument'
  | 'debate_summary'
  | 'debate_resolved'
  | 'collaboration_graph'
  | 'review_result'
  | 'risk_flagged'
  | 'milestone'
  | 'error'

export interface MessageShellMeta {
  name: string
  meta?: string
  avatar?: string
  color?: string
}

export interface MessageRenderSpec {
  type: MessageViewType
  shell: MessageShellMeta
  component: Component
  props: Record<string, unknown>
}

export function resolveMessageType(message: IChatMessage): MessageViewType {
  if (message.role === 'user') return 'user'
  if (message.status === 'error' || message.message_type === 'error') return 'error'

  switch (message.message_type) {
    case 'plan_update':
      return 'team_plan'
    case 'board_started':
      return 'board_banner'
    case 'board_speech':
      return 'board_speech'
    case 'board_summary':
      return 'board_summary'
    case 'board_conclusion':
      return 'board_conclusion'
    case 'debate_started':
      return 'debate_started'
    case 'debate_argument':
      return 'debate_argument'
    case 'debate_summary':
      return 'debate_summary'
    case 'debate_resolved':
      return 'debate_resolved'
    case 'collaboration_graph':
      return 'collaboration_graph'
    case 'review_result':
      return 'review_result'
    case 'risk_flagged':
      return 'risk_flagged'
    case 'milestone':
      return 'milestone'
    default:
      return 'assistant'
  }
}

function formatTime(timestamp: string): string {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
  })
}

export function useMessageRenderer(message: IChatMessage) {
  return computed<MessageRenderSpec>(() => {
    const type = resolveMessageType(message)
    const time = formatTime(message.timestamp)

    switch (type) {
      case 'user':
        return {
          type,
          shell: { name: '用户', meta: time },
          component: UserBubble,
          props: { content: message.content || '' },
        }

      case 'team_plan': {
        const phases = message.plan_phases ?? []
        return {
          type,
          shell: {
            name: message.expert_name || '专家团',
            meta: time,
            avatar: message.expert_avatar,
            color: message.expert_color,
          },
          component: TeamPlanCard,
          props: {
            phases,
            leadName: message.expert_name || 'Lead',
            leadAvatar: message.expert_avatar,
            leadColor: message.expert_color,
          },
        }
      }

      case 'board_banner': {
        const data = message.board_started
        const experts = data?.experts ?? []
        return {
          type,
          shell: { name: '私董会', meta: time },
          component: BoardBannerCard,
          props: {
            topic: data?.topic || message.content || '未命名主题',
            experts,
            maxRounds: data?.max_rounds ?? 5,
            currentRound: message.board_round ?? 1,
          },
        }
      }

      case 'board_speech':
        return {
          type,
          shell: {
            name: message.expert_name || '专家',
            meta: message.board_round ? `第 ${message.board_round} 轮${message.board_role === 'moderator' ? ' · 主持' : ''}` : time,
            avatar: message.expert_avatar,
            color: message.expert_color,
          },
          component: BoardRoundCard,
          props: {
            name: message.expert_name || '专家',
            avatar: message.expert_avatar || '',
            color: message.expert_color,
            round: message.board_round,
            role: message.board_role === 'moderator' ? 'moderator' : 'expert',
            content: message.content || '',
          },
        }

      case 'board_summary':
        return {
          type,
          shell: {
            name: message.expert_name || '主持人',
            meta: message.board_round ? `第 ${message.board_round} 轮 · 小结` : time,
            avatar: message.expert_avatar,
            color: message.expert_color,
          },
          component: BoardRoundCard,
          props: {
            name: message.expert_name || '主持人',
            avatar: message.expert_avatar || '',
            color: message.expert_color,
            round: message.board_round,
            role: 'summary',
            content: message.content || '',
          },
        }

      case 'board_conclusion':
        return {
          type,
          shell: { name: '主持人', meta: time },
          component: BoardConclusionCard,
          props: {
            data: message.board_conclusion ?? {
              summary: message.content || '',
              decision_advice: '',
              total_rounds: message.board_round ?? 0,
              consensus_points: [],
              dissent_points: [],
            },
          },
        }

      case 'debate_started':
        return {
          type,
          shell: {
            name: '辩论',
            avatar: '⚖',
            color: '#722ed1',
            meta: message.debate_topic || '',
          },
          component: DebateBannerCard,
          props: {
            topic: message.debate_topic || '',
            participants: message.debate_participants || [],
            opening: message.debate_opening || message.content,
          },
        }

      case 'debate_argument':
        return {
          type,
          shell: {
            name: message.expert_name || '专家',
            avatar: (message.expert_name || '?')[0],
            color: message.expert_color || '#722ed1',
            meta: `辩论第${message.debate_round || 1}轮`,
          },
          component: DebateArgumentCard,
          props: {
            content: message.content,
            round: message.debate_round || 1,
            expertName: message.expert_name || '',
            expertColor: message.expert_color || '#722ed1',
          },
        }

      case 'debate_summary':
        return {
          type,
          shell: {
            name: message.expert_name || 'Lead',
            avatar: (message.expert_name || 'L')[0],
            color: '#722ed1',
            meta: `第${message.debate_round || 1}轮小结`,
          },
          component: DebateSummaryCard,
          props: {
            content: message.content,
            round: message.debate_round || 1,
            moderatorName: message.debate_moderator || message.expert_name || '',
          },
        }

      case 'debate_resolved': {
        const decisionLabels: Record<string, string> = {
          adopt: '采纳',
          compromise: '折中',
          shelve: '搁置',
          inconclusive: '未决',
        }
        const decision = message.debate_decision || 'inconclusive'
        return {
          type,
          shell: {
            name: '辩论裁决',
            avatar: '⚖',
            color: '#fa8c16',
            meta: decisionLabels[decision] || decision,
          },
          component: DebateConclusionCard,
          props: {
            conclusion: message.content,
            decision,
            rationale: message.debate_rationale || '',
          },
        }
      }

      case 'collaboration_graph': {
        const graphData = message.collaboration_graph ?? {
          contracts: [],
          notices: [],
          reviews: [],
          risks: [],
        }
        return {
          type,
          shell: {
            name: '协作关系图',
            avatar: '◆',
            color: '#1890ff',
            meta: time,
          },
          component: CollaborationGraphCard,
          props: { graphData },
        }
      }

      case 'review_result': {
        const review = message.review_result ?? {
          phase_id: '',
          phase_name: '',
          passed: false,
          feedback: message.content,
          expert: message.expert_name || '',
        }
        return {
          type,
          shell: {
            name: '验收结果',
            avatar: review.passed ? '\u2713' : '\u2717',
            color: review.passed ? '#52c41a' : '#ff4d4f',
            meta: review.phase_name || time,
          },
          component: ReviewResultCard,
          props: { review },
        }
      }

      case 'risk_flagged': {
        const risk = message.risk_flag ?? {
          expert: message.expert_name || '',
          expert_name: message.expert_name || '',
          risk_description: message.content,
          phase_id: '',
          phase_name: '',
        }
        return {
          type,
          shell: {
            name: '风险标记',
            avatar: '!',
            color: '#fa8c16',
            meta: risk.phase_name || time,
          },
          component: RiskFlagCard,
          props: { risk },
        }
      }

      case 'error':
        return {
          type,
          shell: { name: '系统', meta: time },
          component: ErrorCard,
          props: {
            title: '请求失败',
            detail: message.error_detail || message.content || '',
          },
        }

      case 'milestone':
      case 'assistant':
      default:
        return {
          type,
          shell: {
            name: message.expert_name || 'AI Agent',
            meta: time,
            avatar: message.expert_avatar,
            color: message.expert_color,
          },
          component: AssistantText,
          props: { message },
        }
    }
  })
}
