"use client";
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { cn } from '../../../../../../ui/src/lib/utils.mjs';
import { MarkdownContent } from '../../../../../../ui/src/components/markdown-content.mjs';
import { Button } from '../../../../../../ui/src/components/button.mjs';
import { Dialog, DialogContent, DialogTitle } from '../../../../../../ui/src/components/dialog.mjs';
import { Bot, FileText, X, Send, Pencil, Check, Copy, RefreshCw, User } from 'lucide-react';
import { isToolUIPart, getToolName } from 'ai';
import { useState, useRef, useEffect, useMemo } from 'react';
import { usePluginOverrides } from '@btst/stack/context';
import { AI_CHAT_LOCALIZATION } from '../localization/index.mjs';
import { ToolCallDisplay } from './tool-call-display.mjs';
import 'highlight.js/styles/panda-syntax-light.css';
import completeMarkdown from 'remend';

const DefaultLink = (props) => /* @__PURE__ */ jsx("a", { ...props });
const DefaultImage = (props) => /* @__PURE__ */ jsx("img", { ...props });
function ClickableImage({
  src,
  alt,
  width = 200,
  height = 200,
  className,
  ImageComponent
}) {
  const [isOpen, setIsOpen] = useState(false);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick: () => setIsOpen(true),
        className: "cursor-zoom-in focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-md overflow-hidden",
        style: { width, height },
        children: /* @__PURE__ */ jsx(
          ImageComponent,
          {
            src,
            alt,
            width,
            height,
            className: cn(
              "object-cover hover:opacity-90 transition-opacity",
              className
            )
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: setIsOpen, children: /* @__PURE__ */ jsxs(
      DialogContent,
      {
        className: "max-w-[90vw] max-h-[90vh] p-2 sm:max-w-[90vw]",
        showCloseButton: true,
        children: [
          /* @__PURE__ */ jsx(DialogTitle, { className: "sr-only", children: alt }),
          /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center", children: /* @__PURE__ */ jsx(
            "img",
            {
              src,
              alt,
              className: "max-w-full max-h-[85vh] object-contain rounded-md"
            }
          ) })
        ]
      }
    ) })
  ] });
}
function ChatMessage({
  message,
  isStreaming = false,
  variant = "default",
  onRetry,
  onEdit,
  isRetrying = false
}) {
  const isUser = message.role === "user";
  const {
    Link,
    Image,
    localization: customLocalization,
    toolRenderers
  } = usePluginOverrides(
    "ai-chat",
    {}
  );
  const localization = { ...AI_CHAT_LOCALIZATION, ...customLocalization };
  const ImageComponent = Image ?? DefaultImage;
  const [copied, setCopied] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState("");
  const editTextareaRef = useRef(null);
  useEffect(() => {
    if (isEditing && editTextareaRef.current) {
      editTextareaRef.current.style.height = "auto";
      editTextareaRef.current.style.height = `${editTextareaRef.current.scrollHeight}px`;
      editTextareaRef.current.focus();
    }
  }, [isEditing, editText]);
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(textContent);
      setCopied(true);
      setTimeout(() => setCopied(false), 2e3);
    } catch (err) {
      console.error("Failed to copy text:", err);
    }
  };
  const handleStartEdit = () => {
    setEditText(textContent);
    setIsEditing(true);
  };
  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditText("");
  };
  const handleSaveEdit = () => {
    if (editText.trim() && onEdit) {
      onEdit(editText.trim());
      setIsEditing(false);
      setEditText("");
    }
  };
  const handleEditKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSaveEdit();
    } else if (e.key === "Escape") {
      handleCancelEdit();
    }
  };
  const textContent = useMemo(() => {
    if (message.parts && Array.isArray(message.parts)) {
      return message.parts.filter((part) => part.type === "text").map((part) => part.text).join("");
    }
    return "";
  }, [message.parts]);
  const imageParts = useMemo(() => {
    if (message.parts && Array.isArray(message.parts)) {
      return message.parts.filter(
        (part) => part.type === "file" && part.mediaType?.startsWith("image/")
      );
    }
    return [];
  }, [message.parts]);
  const fileParts = useMemo(() => {
    if (message.parts && Array.isArray(message.parts)) {
      return message.parts.filter(
        (part) => part.type === "file" && !part.mediaType?.startsWith("image/")
      );
    }
    return [];
  }, [message.parts]);
  const toolParts = useMemo(() => {
    if (message.parts && Array.isArray(message.parts)) {
      return message.parts.filter((part) => isToolUIPart(part));
    }
    return [];
  }, [message.parts]);
  const displayContent = useMemo(() => {
    if (!textContent) return "";
    if (isStreaming && !isUser) {
      return completeMarkdown(textContent);
    }
    return textContent;
  }, [textContent, isStreaming, isUser]);
  const isCompact = variant === "compact";
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "flex gap-3 w-full",
        isCompact ? "mb-3" : "mb-4",
        isUser ? "justify-end" : "justify-start"
      ),
      "aria-label": isUser ? localization.A11Y_USER_MESSAGE : localization.A11Y_ASSISTANT_MESSAGE,
      children: [
        !isUser && /* @__PURE__ */ jsx(
          "div",
          {
            className: cn(
              "rounded-full bg-muted flex items-center justify-center shrink-0",
              isCompact ? "w-7 h-7" : "w-8 h-8"
            ),
            children: /* @__PURE__ */ jsx(Bot, { className: cn(isCompact ? "w-4 h-4" : "w-5 h-5") })
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 max-w-[80%] group", children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: cn(
                "rounded-lg",
                isCompact ? "px-3 py-2" : "px-4 py-3",
                isUser ? "bg-primary text-primary-foreground" : "bg-muted"
              ),
              children: isUser ? (
                // User messages: files + images + text (or edit mode)
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  fileParts.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: fileParts.map((part, index) => /* @__PURE__ */ jsxs(
                    "a",
                    {
                      href: part.url,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      className: "flex items-center gap-2 px-3 py-2 rounded-md bg-primary-foreground/10 hover:bg-primary-foreground/20 transition-colors",
                      children: [
                        /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4 shrink-0" }),
                        /* @__PURE__ */ jsx("span", { className: "text-xs truncate max-w-[150px]", children: part.filename || "File" })
                      ]
                    },
                    index
                  )) }),
                  imageParts.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: imageParts.map((part, index) => /* @__PURE__ */ jsx(
                    ClickableImage,
                    {
                      src: part.url,
                      alt: part.filename || `Attached image ${index + 1}`,
                      width: 150,
                      height: 150,
                      className: "rounded-md",
                      ImageComponent
                    },
                    index
                  )) }),
                  isEditing ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                    /* @__PURE__ */ jsx(
                      "textarea",
                      {
                        ref: editTextareaRef,
                        value: editText,
                        onChange: (e) => setEditText(e.target.value),
                        onKeyDown: handleEditKeyDown,
                        className: cn(
                          "w-full min-w-[200px] resize-none rounded-md border-0 bg-primary-foreground/10 p-2 text-sm",
                          "focus:outline-none focus:ring-1 focus:ring-primary-foreground/30",
                          "text-primary-foreground placeholder:text-primary-foreground/50"
                        ),
                        rows: 1
                      }
                    ),
                    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2", children: [
                      /* @__PURE__ */ jsx(
                        Button,
                        {
                          type: "button",
                          size: "icon-sm",
                          variant: "ghost",
                          onClick: handleCancelEdit,
                          className: "h-7 w-7 text-primary-foreground hover:bg-primary-foreground/20",
                          title: localization.MESSAGE_CANCEL,
                          children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
                        }
                      ),
                      /* @__PURE__ */ jsx(
                        Button,
                        {
                          type: "button",
                          size: "icon-sm",
                          variant: "ghost",
                          onClick: handleSaveEdit,
                          disabled: !editText.trim(),
                          className: "h-7 w-7 text-primary-foreground hover:bg-primary-foreground/20 disabled:opacity-50",
                          title: localization.MESSAGE_SAVE,
                          children: /* @__PURE__ */ jsx(Send, { className: "h-4 w-4" })
                        }
                      )
                    ] })
                  ] }) : textContent && /* @__PURE__ */ jsx(
                    "p",
                    {
                      className: cn(
                        "whitespace-pre-wrap wrap-break-word",
                        isCompact ? "text-sm" : "text-sm"
                      ),
                      children: textContent
                    }
                  )
                ] })
              ) : (
                // Assistant messages: rendered markdown + files + images + tool calls
                /* @__PURE__ */ jsxs("div", { className: "wrap-break-word space-y-2", children: [
                  fileParts.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: fileParts.map((part, index) => /* @__PURE__ */ jsxs(
                    "a",
                    {
                      href: part.url,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      className: "flex items-center gap-2 px-3 py-2 rounded-md bg-muted-foreground/10 hover:bg-muted-foreground/20 transition-colors border",
                      children: [
                        /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
                        /* @__PURE__ */ jsx("span", { className: "text-xs truncate max-w-[150px]", children: part.filename || "File" })
                      ]
                    },
                    index
                  )) }),
                  imageParts.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: imageParts.map((part, index) => /* @__PURE__ */ jsx(
                    ClickableImage,
                    {
                      src: part.url,
                      alt: part.filename || `Image ${index + 1}`,
                      width: 200,
                      height: 200,
                      className: "rounded-md",
                      ImageComponent
                    },
                    index
                  )) }),
                  toolParts.length > 0 && /* @__PURE__ */ jsx("div", { className: "space-y-2", children: toolParts.map((part) => {
                    const toolName = getToolName(part);
                    const toolCallId = part.toolCallId;
                    const state = part.state;
                    const input = part.input;
                    const output = part.output;
                    const errorText = part.errorText;
                    const isLoading = state === "input-streaming" || state === "input-available";
                    const toolCallProps = {
                      toolCallId,
                      toolName,
                      state,
                      input,
                      output,
                      errorText,
                      isLoading
                    };
                    const CustomRenderer = toolRenderers?.[toolName];
                    if (CustomRenderer) {
                      return /* @__PURE__ */ jsx(CustomRenderer, { ...toolCallProps }, toolCallId);
                    }
                    return /* @__PURE__ */ jsx(ToolCallDisplay, { ...toolCallProps }, toolCallId);
                  }) }),
                  displayContent ? /* @__PURE__ */ jsx(
                    MarkdownContent,
                    {
                      markdown: displayContent,
                      variant: "chat",
                      LinkComponent: Link ?? DefaultLink,
                      ImageComponent
                    }
                  ) : imageParts.length === 0 && fileParts.length === 0 && toolParts.length === 0 ? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "..." }) : null
                ] })
              )
            }
          ),
          !isStreaming && !isEditing && /* @__PURE__ */ jsx(
            "div",
            {
              className: cn(
                "flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",
                isUser ? "justify-end" : "justify-start"
              ),
              children: isUser ? (
                // User message actions: Edit
                onEdit && /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    size: "icon-sm",
                    variant: "ghost",
                    onClick: handleStartEdit,
                    className: "h-7 w-7 bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50",
                    title: localization.MESSAGE_EDIT,
                    children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
                  }
                )
              ) : (
                // Assistant message actions: Copy and Retry
                /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      size: "icon-sm",
                      variant: "ghost",
                      onClick: handleCopy,
                      className: "h-7 w-7 bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50",
                      title: copied ? localization.MESSAGE_COPIED : localization.MESSAGE_COPY,
                      children: copied ? /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3.5 w-3.5" })
                    }
                  ),
                  onRetry && /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      size: "icon-sm",
                      variant: "ghost",
                      onClick: onRetry,
                      disabled: isRetrying,
                      className: "h-7 w-7 bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50 disabled:opacity-50",
                      title: localization.MESSAGE_RETRY,
                      children: /* @__PURE__ */ jsx(
                        RefreshCw,
                        {
                          className: cn(
                            "h-3.5 w-3.5",
                            isRetrying && "animate-spin"
                          )
                        }
                      )
                    }
                  )
                ] })
              )
            }
          )
        ] }),
        isUser && /* @__PURE__ */ jsx(
          "div",
          {
            className: cn(
              "rounded-full bg-primary flex items-center justify-center shrink-0 text-primary-foreground",
              isCompact ? "w-7 h-7" : "w-8 h-8"
            ),
            children: /* @__PURE__ */ jsx(User, { className: cn(isCompact ? "w-4 h-4" : "w-5 h-5") })
          }
        )
      ]
    }
  );
}

export { ChatMessage };
