import { memo, type ReactNode } from "react"
import { Space, Tag, Typography } from "antd"
import RichTextContent from "./RichTextContent"
import type { TicketSenderType } from "../api/tickets"

const { Text } = Typography

export interface MessageItemData {
  id: number
  sender_type: TicketSenderType
  sender_name?: string | null
  content: string
  is_internal?: boolean
  created_at?: string | null
}

const SENDER_META_USER: Record<TicketSenderType, { label: string; color: string }> = {
  user: { label: "我", color: "blue" },
  admin: { label: "客服", color: "green" },
  system: { label: "系统", color: "default" },
}

const SENDER_META_ADMIN: Record<TicketSenderType, { label: string; color: string }> = {
  user: { label: "用户", color: "blue" },
  admin: { label: "支持", color: "green" },
  system: { label: "系统", color: "default" },
}

function formatDate(value?: string | null) {
  if (!value) return "-"
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString("zh-CN", { hour12: false })
}

interface TicketMessageItemProps {
  message: MessageItemData
  /** "user" or "admin" — changes the sender labels */
  mode?: "user" | "admin"
  /** Extra content to render before the rich text, e.g. unread badge */
  headerExtra?: ReactNode
}

/**
 * Memoized single message row. Only re-renders when the message data changes.
 * This prevents the entire message list from re-rendering on polling updates.
 */
const TicketMessageItem = memo(function TicketMessageItem({
  message,
  mode = "user",
  headerExtra,
}: TicketMessageItemProps) {
  const meta =
    mode === "admin" ? SENDER_META_ADMIN[message.sender_type] : SENDER_META_USER[message.sender_type]

  return (
    <div
      style={{
        borderBottom: "1px solid #f0f0f0",
        paddingBottom: 16,
        opacity: message.is_internal ? 0.82 : 1,
      }}
    >
      <Space align="center" wrap style={{ marginBottom: 8 }}>
        <Tag color={message.is_internal ? "purple" : meta.color}>
          {message.is_internal ? "内部备注" : meta.label}
        </Tag>
        {message.sender_name && <Text strong>{message.sender_name}</Text>}
        <Text type="secondary">{formatDate(message.created_at)}</Text>
        {headerExtra}
      </Space>
      <RichTextContent value={message.content} admin={mode === "admin"} />
    </div>
  )
})

export default TicketMessageItem
