'use client'

import { useState, useCallback } from 'react'
import { Copy, Check, Trash } from '@phosphor-icons/react'
import { cn } from '@/lib/utils'
import { MarkdownRenderer } from '../../shared/markdown-renderer'
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { ToolCallDisplay } from './tool-call-display'
import type { AssistantMessageProps, AssistantActionBarProps } from './types'

export function AssistantMessage({ 
  content,
  messageId,
  toolInvocations,
  isStreaming,
  onDeleteMessage,
  onNavigate,
  onNavigateToDocPage,
  onOpenFile
}: AssistantMessageProps) {
  return (
    <div 
      className={cn(
        "aui-assistant-message-root",
        "fade-in slide-in-from-bottom-1 animate-in duration-150",
        "relative mx-auto w-full max-w-[var(--thread-max-width)] py-3"
      )}
      data-role="assistant"
    >
      {/* Text content */}
      {content && (
        <div className="aui-assistant-message-content wrap-break-word px-2 text-foreground leading-relaxed">
          <div className="prose prose-sm dark:prose-invert max-w-none">
            <MarkdownRenderer content={content} />
          </div>
        </div>
      )}
      
      {/* Tool invocations */}
      {toolInvocations && toolInvocations.length > 0 && (
        <div className="mt-2 px-2 space-y-1">
          {toolInvocations.map((tool) => (
            <ToolCallDisplay key={tool.toolCallId} tool={tool} onNavigate={onNavigate} onNavigateToDocPage={onNavigateToDocPage} onOpenFile={onOpenFile} />
          ))}
        </div>
      )}

      {/* Action bar - only show when streaming is finished */}
      {!isStreaming && (
        <div className="aui-assistant-message-footer mt-1 px-2 flex justify-end">
          <AssistantActionBar content={content} messageId={messageId} onDeleteMessage={onDeleteMessage} />
        </div>
      )}
    </div>
  )
}

function AssistantActionBar({ 
  content,
  messageId,
  onDeleteMessage 
}: AssistantActionBarProps) {
  const [copied, setCopied] = useState(false)

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(content)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error('Failed to copy:', err)
    }
  }, [content])

  const handleDelete = useCallback(() => {
    if (messageId && onDeleteMessage) {
      onDeleteMessage(messageId)
    }
  }, [messageId, onDeleteMessage])

  return (
    <div className={cn(
      "aui-assistant-action-bar-root",
      "flex gap-1 text-muted-foreground"
    )}>
      <Tooltip>
        <TooltipTrigger asChild>
          <button
            onClick={handleCopy}
            className="aui-button-icon size-6 p-1 rounded hover:bg-accent hover:text-foreground transition-colors"
            aria-label={copied ? "Copied" : "Copy"}
          >
            {copied ? <Check className="size-4" weight="bold" /> : <Copy className="size-4" />}
          </button>
        </TooltipTrigger>
        <TooltipContent>{copied ? "Copied!" : "Copy"}</TooltipContent>
      </Tooltip>
      
      {messageId && onDeleteMessage && (
        <Tooltip>
          <TooltipTrigger asChild>
            <button
              onClick={handleDelete}
              className="aui-button-icon size-6 p-1 rounded hover:bg-accent hover:text-foreground transition-colors"
              aria-label="Delete message"
            >
              <Trash className="size-4" />
            </button>
          </TooltipTrigger>
          <TooltipContent>Delete message</TooltipContent>
        </Tooltip>
      )}
    </div>
  )
}
