import type { ChatMessage, Profile } from '../types'
import { escapeHtml, formatDateTime, getRkeyFromUri, getAuthorityFromUri } from '../lib/util'
import { buildAuthorMap, resolveAuthorDid, chatTypeSlug, getTranslatedContent } from './chat'

export type { ChatCollectionEntry } from './chat'

const formatChatTime = formatDateTime

// Render chat threads list (conversations this user started)
export function renderChatThreadList(
  messages: ChatMessage[],
  userDid: string,
  userHandle: string,
  botDid: string,
  botHandle: string,
  userProfile?: Profile | null,
  botProfile?: Profile | null,
  pds?: string,
  chatCollection: string = 'ai.syui.log.chat'
): string {
  // Build set of all message URIs
  const allUris = new Set(messages.map(m => m.uri))

  // Find root messages by this user:
  // 1. No root field (explicit start of conversation)
  // 2. Or root points to non-existent message (orphaned, treat as root)
  //    For orphaned roots, only keep the oldest message per orphaned root URI
  const orphanedRootFirstMsg = new Map<string, ChatMessage>()
  const rootMessages: ChatMessage[] = []

  for (const msg of messages) {
    if (resolveAuthorDid(getAuthorityFromUri(msg.uri)) !== userDid) continue

    if (!msg.value.root) {
      // No root = explicit conversation start
      rootMessages.push(msg)
    } else if (!allUris.has(msg.value.root)) {
      // Orphaned root - keep only the oldest message per orphaned root
      const existing = orphanedRootFirstMsg.get(msg.value.root)
      if (!existing || new Date(msg.value.publishedAt) < new Date(existing.value.publishedAt)) {
        orphanedRootFirstMsg.set(msg.value.root, msg)
      }
    }
  }

  // Add orphaned root representatives
  for (const msg of orphanedRootFirstMsg.values()) {
    rootMessages.push(msg)
  }

  if (rootMessages.length === 0) {
    return '<p class="no-posts">No chat threads yet.</p>'
  }

  const authors = buildAuthorMap(userDid, userHandle, botDid, botHandle, userProfile, botProfile, pds)

  // Sort by publishedAt (newest first)
  const sorted = [...rootMessages].sort((a, b) =>
    new Date(b.value.publishedAt).getTime() - new Date(a.value.publishedAt).getTime()
  )

  const items = sorted.map(msg => {
    const authorDid = resolveAuthorDid(getAuthorityFromUri(msg.uri))
    const time = formatChatTime(msg.value.publishedAt)
    const rkey = getRkeyFromUri(msg.uri)
    const author = authors.get(authorDid) || { did: authorDid, handle: authorDid.slice(0, 20) + '...' }

    const avatarHtml = author.avatarUrl
      ? `<img class="chat-avatar" src="${author.avatarUrl}" alt="@${escapeHtml(author.handle)}">`
      : `<div class="chat-avatar-placeholder"></div>`

    // Truncate content for preview (use translated content, show first 3 lines)
    const displayContent = getTranslatedContent(msg)
    const lines = displayContent.split('\n').slice(0, 3)
    const preview = lines.join('\n')

    return `
      <a href="/@${userHandle}/at/chat/${chatTypeSlug(chatCollection)}/${rkey}" class="chat-thread-item">
        <div class="chat-avatar-col">
          ${avatarHtml}
        </div>
        <div class="chat-thread-content">
          <div class="chat-thread-header">
            <span class="chat-author">@${escapeHtml(author.handle)}</span>
            <span class="chat-type-badge" data-type="${chatTypeSlug(chatCollection)}">${chatTypeSlug(chatCollection)}</span>
            <span class="chat-time">${time}</span>
          </div>
          <div class="chat-thread-preview">${escapeHtml(preview)}</div>
        </div>
      </a>
    `
  }).join('')

  return `<div class="chat-thread-list">${items}</div>`
}

// Render unified chat list page with filter buttons
export function renderChatListPage(
  collections: import('./chat').ChatCollectionEntry[],
  userDid: string,
  userHandle: string,
  botDid: string,
  botHandle: string,
  userProfile?: Profile | null,
  botProfile?: Profile | null,
  pds?: string
): string {
  // Merge all collections into a single list
  const allMessages: ChatMessage[] = []
  const messageCollectionMap = new Map<string, string>()

  for (const c of collections) {
    for (const msg of c.messages) {
      allMessages.push(msg)
      messageCollectionMap.set(msg.uri, c.collection)
    }
  }

  // Build author map with first collection's params (all share same users)
  const authors = buildAuthorMap(userDid, userHandle, botDid, botHandle, userProfile, botProfile, pds)

  // Find root messages (same logic as renderChatThreadList)
  const allUris = new Set(allMessages.map(m => m.uri))
  const orphanedRootFirstMsg = new Map<string, ChatMessage>()
  const rootMessages: ChatMessage[] = []

  for (const msg of allMessages) {
    if (resolveAuthorDid(getAuthorityFromUri(msg.uri)) !== userDid) continue

    if (!msg.value.root) {
      rootMessages.push(msg)
    } else if (!allUris.has(msg.value.root)) {
      const existing = orphanedRootFirstMsg.get(msg.value.root)
      if (!existing || new Date(msg.value.publishedAt) < new Date(existing.value.publishedAt)) {
        orphanedRootFirstMsg.set(msg.value.root, msg)
      }
    }
  }

  for (const msg of orphanedRootFirstMsg.values()) {
    rootMessages.push(msg)
  }

  if (rootMessages.length === 0) {
    return '<div class="chat-container"><p class="no-posts">No chat threads yet.</p></div>'
  }

  // Sort by publishedAt (newest first)
  const sorted = [...rootMessages].sort((a, b) =>
    new Date(b.value.publishedAt).getTime() - new Date(a.value.publishedAt).getTime()
  )

  const items = sorted.map(msg => {
    const authorDid = resolveAuthorDid(getAuthorityFromUri(msg.uri))
    const time = formatChatTime(msg.value.publishedAt)
    const rkey = getRkeyFromUri(msg.uri)
    const author = authors.get(authorDid) || { did: authorDid, handle: authorDid.slice(0, 20) + '...' }
    const collection = messageCollectionMap.get(msg.uri) || 'ai.syui.log.chat'
    const slug = chatTypeSlug(collection)

    const avatarHtml = author.avatarUrl
      ? `<img class="chat-avatar" src="${author.avatarUrl}" alt="@${escapeHtml(author.handle)}">`
      : `<div class="chat-avatar-placeholder"></div>`

    const displayContent = getTranslatedContent(msg)
    const lines = displayContent.split('\n').slice(0, 3)
    const preview = lines.join('\n')

    return `
      <a href="/@${userHandle}/at/chat/${slug}/${rkey}" class="chat-thread-item">
        <div class="chat-avatar-col">
          ${avatarHtml}
        </div>
        <div class="chat-thread-content">
          <div class="chat-thread-header">
            <span class="chat-author">@${escapeHtml(author.handle)}</span>
            <span class="chat-type-badge" data-type="${slug}">${slug}</span>
            <span class="chat-time">${time}</span>
          </div>
          <div class="chat-thread-preview">${escapeHtml(preview)}</div>
        </div>
      </a>
    `
  }).join('')

  return `<div class="chat-container"><div class="chat-thread-list">${items}</div></div>`
}
