'use client'

import * as React from 'react'
import { cn } from '../../lib/utils'
import { ChatThread } from '../chat/ChatThread'
import { ChatComposer } from '../chat/ChatComposer'
import type { ChatMessageData } from '../chat/types'

export interface ConversationTimelineProps {
  /** The agent-shaped timeline entries (already chat-shaped: status/kind/toolName). */
  entries: ChatMessageData[]
  /** Header title. */
  title?: string
  /** 0..100 progress bar shown under the header (omit to hide). */
  progressPercent?: number
  /** Short status label shown in the header. */
  statusLabel?: string
  /** Called with the composed message text. Sending state is tracked internally. */
  onSend?: (text: string) => void | Promise<void>
  /** The agent is working / entries are loading — shows the working indicator. */
  isLoading?: boolean
  /** Load older entries (renders a "Load more" control when `hasMore`). */
  onLoadMore?: () => void
  hasMore?: boolean
  composerPlaceholder?: string
  /** Rendered when there are no entries. */
  emptyState?: React.ReactNode
  /** Custom message-body renderer passed through to ChatThread (e.g. markdown). */
  renderContent?: (content: string, message: ChatMessageData) => React.ReactNode
  className?: string
}

/**
 * The "steer the agent" surface: a scrolling timeline of agent events plus a
 * composer that sends a message back to the agent. Built on the existing
 * ChatThread / ChatComposer, so it inherits their auto-scroll, streaming
 * indicators, tool/status rows, and keyboard handling. Fully generic — it takes
 * `ChatMessageData[]` and an `onSend` callback; it knows nothing about the
 * transport or any app model.
 */
export function ConversationTimeline({
  entries,
  title,
  progressPercent,
  statusLabel,
  onSend,
  isLoading = false,
  onLoadMore,
  hasMore = false,
  composerPlaceholder = 'Message the agent…',
  emptyState,
  renderContent,
  className,
}: ConversationTimelineProps) {
  const [sending, setSending] = React.useState(false)

  const handleSubmit = React.useCallback(
    (text: string) => {
      if (!onSend) return
      const result = onSend(text)
      if (result && typeof (result as Promise<void>).then === 'function') {
        setSending(true)
        void (result as Promise<void>).finally(() => setSending(false))
      }
    },
    [onSend],
  )

  const showHeader = !!title || !!statusLabel || progressPercent != null

  return (
    <div className={cn('flex h-full flex-col overflow-hidden rounded-lg border border-border bg-card', className)}>
      {showHeader && (
        <div className="flex-shrink-0 border-b border-border px-4 py-3">
          <div className="flex items-center justify-between gap-2">
            {title && <h3 className="truncate text-sm font-semibold text-foreground">{title}</h3>}
            {statusLabel && <span className="text-xs text-muted-foreground">{statusLabel}</span>}
          </div>
          {progressPercent != null && (
            <div className="mt-2">
              <div className="mb-1 flex items-center justify-between text-xs text-muted-foreground">
                <span>Progress</span>
                <span>{Math.round(progressPercent)}%</span>
              </div>
              <div className="h-2 overflow-hidden rounded-full bg-muted">
                <div
                  className="h-full rounded-full bg-primary transition-[width] duration-500"
                  style={{ width: `${Math.max(0, Math.min(100, progressPercent))}%` }}
                  role="progressbar"
                  aria-valuemin={0}
                  aria-valuemax={100}
                  aria-valuenow={Math.round(progressPercent)}
                />
              </div>
            </div>
          )}
        </div>
      )}

      <div className="flex min-h-0 flex-1 flex-col">
        {hasMore && onLoadMore && (
          <div className="flex-shrink-0 border-b border-border p-2 text-center">
            <button
              type="button"
              onClick={onLoadMore}
              className="text-xs text-primary transition-colors hover:underline"
            >
              Load earlier messages
            </button>
          </div>
        )}
        <ChatThread
          messages={entries}
          busy={isLoading}
          emptyState={emptyState}
          renderContent={renderContent}
          className="flex-1"
        />
      </div>

      {onSend && (
        <ChatComposer
          onSubmit={handleSubmit}
          placeholder={composerPlaceholder}
          busy={sending}
          className="flex-shrink-0"
        />
      )}
    </div>
  )
}
