import { cn } from "@/lib/utils";
import type { Message } from "@/lib/api";
import { MarkdownContent } from "@/components/markdown/markdown-content";

type Props = {
  messages: Message[];
  isLoading: boolean;
  isSending: boolean;
};

export function ChatMessagesPanel({ messages, isLoading, isSending }: Props) {
  const hasPendingAssistant = messages.some((message) => message.id.startsWith("temp-assistant-"));

  return (
    <>
      {isLoading && messages.length === 0 ? <p className="text-sm text-muted-foreground">Loading messages...</p> : null}
      <div className="mx-auto max-w-3xl space-y-6">
        {messages.map((message) => {
          const isUser = message.role === "user";
          const isPendingAssistant = message.id.startsWith("temp-assistant-") && isSending;
          return (
            <div key={message.id} className={cn("flex", isUser ? "justify-end" : "justify-start")}>
              <div
                className={cn(
                  "max-w-[85%]",
                  isUser ? "rounded-2xl bg-violet-900/80 px-4 py-3 text-sm leading-6 text-fuchsia-50" : "text-base leading-7 text-fuchsia-100"
                )}
              >
                {isPendingAssistant ? (
                  <span className="inline-flex items-center gap-1" aria-label="Assistant is typing" role="status">
                    <span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:0ms]" />
                    <span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:140ms]" />
                    <span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:280ms]" />
                  </span>
                ) : (
                  <MarkdownContent
                    markdown={message.content}
                    className={cn("[&_a]:text-inherit [&_a]:underline", isUser ? "leading-[1.78] text-fuchsia-50" : "leading-[1.82] text-fuchsia-100")}
                  />
                )}
              </div>
            </div>
          );
        })}
        {isSending && !hasPendingAssistant ? (
          <div className="flex justify-start">
            <div className="max-w-[85%] text-base leading-7 text-fuchsia-100">
              <span className="inline-flex items-center gap-1" aria-label="Assistant is typing" role="status">
                <span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:0ms]" />
                <span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:140ms]" />
                <span className="inline-block h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:280ms]" />
              </span>
            </div>
          </div>
        ) : null}
      </div>
    </>
  );
}
