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

const formatChatTime = formatDateTime

// Render single chat thread (full conversation)
export function renderChatThread(
  messages: ChatMessage[],
  rootRkey: string,
  userDid: string,
  userHandle: string,
  botDid: string,
  botHandle: string,
  userProfile?: Profile | null,
  botProfile?: Profile | null,
  pds?: string,
  chatCollection: string = 'ai.syui.log.chat',
  loggedInDid?: string | null
): string {
  // Find root message
  const rootUri = `at://${userDid}/${chatCollection}/${rootRkey}`
  const rootMsg = messages.find(m => m.uri === rootUri)

  if (!rootMsg) {
    return '<p class="error">Chat thread not found.</p>'
  }

  // Find all messages in this thread
  // 1. The root message itself
  // 2. Messages with root === rootUri (direct children)
  // 3. If this is an orphaned root (root points to non-existent), find siblings with same original root
  const originalRoot = rootMsg.value.root
  const allUris = new Set(messages.map(m => m.uri))
  const isOrphanedRoot = originalRoot && !allUris.has(originalRoot)

  const threadMessages = messages.filter(msg => {
    // Include the root message itself
    if (msg.uri === rootUri) return true
    // Include messages that point to this as root
    if (msg.value.root === rootUri) return true
    // If orphaned, include messages with the same original root
    if (isOrphanedRoot && msg.value.root === originalRoot) return true
    return false
  })

  if (threadMessages.length === 0) {
    return '<p class="error">No messages in this thread.</p>'
  }

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

  // Sort by publishedAt
  const sorted = [...threadMessages].sort((a, b) =>
    new Date(a.value.publishedAt).getTime() - new Date(b.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>`

    const displayContent = getTranslatedContent(msg)
    const content = renderMarkdown(displayContent)
    const recordLink = `/@${author.handle}/at/collection/${chatCollection}/${rkey}`
    const canEdit = loggedInDid && authorDid === loggedInDid
    const editLink = `/@${userHandle}/at/chat/${chatTypeSlug(chatCollection)}/${rkey}/edit`

    return `
      <article class="chat-message">
        <div class="chat-avatar-col">
          ${avatarHtml}
        </div>
        <div class="chat-content-col">
          <div class="chat-message-header">
            <a href="/@${author.handle}" class="chat-author">@${escapeHtml(author.handle)}</a>
            <a href="${recordLink}" class="chat-time">${time}</a>
            ${canEdit ? `<a href="${editLink}" class="chat-edit-btn">edit</a>` : ''}
          </div>
          <div class="chat-content">${content}</div>
        </div>
      </article>
    `
  }).join('')

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

// Render chat thread page
export function renderChatThreadPage(
  messages: ChatMessage[],
  rootRkey: string,
  userDid: string,
  userHandle: string,
  botDid: string,
  botHandle: string,
  userProfile?: Profile | null,
  botProfile?: Profile | null,
  pds?: string,
  chatCollection: string = 'ai.syui.log.chat',
  loggedInDid?: string | null
): string {
  const thread = renderChatThread(messages, rootRkey, userDid, userHandle, botDid, botHandle, userProfile, botProfile, pds, chatCollection, loggedInDid)
  return `<div class="chat-container">${thread}</div>`
}

// Render chat edit form
export function renderChatEditForm(
  message: ChatMessage,
  collection: string,
  userHandle: string
): string {
  const rkey = message.uri.split('/').pop() || ''
  const content = message.value.content.text

  return `
    <div class="chat-edit-container">
      <h2>Edit Chat Message</h2>
      <form class="chat-edit-form" id="chat-edit-form">
        <textarea
          class="chat-edit-content"
          id="chat-edit-content"
          rows="10"
          required
        >${escapeHtml(content)}</textarea>
        <div class="chat-edit-footer">
          <span class="chat-edit-collection">${collection}</span>
          <div class="chat-edit-buttons">
            <a href="/@${userHandle}/at/chat/${chatTypeSlug(collection)}/${rkey}" class="chat-edit-cancel">Cancel</a>
            <button type="submit" class="chat-edit-save" id="chat-edit-save" data-rkey="${rkey}">Save</button>
          </div>
        </div>
      </form>
      <div id="chat-edit-status" class="chat-edit-status"></div>
    </div>
  `
}
