"use client";

import { Bot, User } from "lucide-react";
import { RemindMeButton } from "@/components/reminders/remind-me-button";
import { cn } from "@/lib/utils";

export interface ChatMessageData {
  id: string;
  role: "user" | "assistant";
  content: string;
}

interface ChatMessageProps {
  message: ChatMessageData;
}

export function ChatMessage({ message }: ChatMessageProps) {
  const isUser = message.role === "user";

  return (
    <div
      className={cn(
        "group flex gap-3 py-4",
        isUser && "flex-row-reverse"
      )}
    >
      {/* Avatar */}
      <div
        className={cn(
          "flex items-center justify-center h-8 w-8 rounded-full shrink-0",
          isUser ? "bg-primary text-primary-foreground" : "bg-muted"
        )}
      >
        {isUser ? (
          <User className="h-4 w-4" />
        ) : (
          <Bot className="h-4 w-4" />
        )}
      </div>

      {/* Content */}
      <div
        className={cn(
          "flex-1 min-w-0 max-w-[85%]",
          isUser && "flex flex-col items-end"
        )}
      >
        <div
          className={cn(
            "rounded-2xl px-4 py-2.5 text-sm leading-relaxed",
            isUser
              ? "bg-primary text-primary-foreground rounded-br-md"
              : "bg-muted rounded-bl-md"
          )}
        >
          <div className="prose-sm prose-neutral max-w-none [&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0.5 [&_pre]:my-2 [&_pre]:rounded-lg [&_pre]:bg-black/5 [&_pre]:p-3 [&_code]:text-xs whitespace-pre-wrap">
            <MarkdownContent content={message.content} />
          </div>
        </div>
        <div className={cn("mt-1 opacity-0 transition-opacity hover:opacity-100", !isUser && "group-hover:opacity-100")}>
          <RemindMeButton
            body={message.content.slice(0, 240)}
            className="border-border bg-transparent px-2.5 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
            label="Remind me"
            sourceId={message.id}
            sourceTitle={`${isUser ? "Meine Nachricht" : "AI Antwort"}: ${message.content.slice(0, 42)}`}
            sourceType="chat_message"
            sourceUrl="/chat"
            title="Chat Reminder"
          />
        </div>
      </div>
    </div>
  );
}

function MarkdownContent({ content }: { content: string }) {
  if (!content) return null;

  const lines = content.split("\n");

  return (
    <>
      {lines.map((line, i) => {
        if (line.startsWith("### "))
          return <h4 key={i} className="font-semibold mt-2 mb-1">{formatInline(line.slice(4))}</h4>;
        if (line.startsWith("## "))
          return <h3 key={i} className="font-semibold text-base mt-2 mb-1">{formatInline(line.slice(3))}</h3>;
        if (line.startsWith("# "))
          return <h2 key={i} className="font-bold text-base mt-2 mb-1">{formatInline(line.slice(2))}</h2>;
        if (line.match(/^[-*] /))
          return <div key={i} className="flex gap-2"><span>•</span><span>{formatInline(line.slice(2))}</span></div>;
        if (line.match(/^\d+\. /))
          return <div key={i} className="flex gap-2"><span>{line.match(/^\d+/)![0]}.</span><span>{formatInline(line.replace(/^\d+\.\s*/, ""))}</span></div>;
        if (!line.trim()) return <div key={i} className="h-2" />;
        return <p key={i}>{formatInline(line)}</p>;
      })}
    </>
  );
}

function formatInline(text: string) {
  const parts = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|~~[^~]+~~)/g);
  return parts.map((part, i) => {
    if (part.startsWith("`") && part.endsWith("`"))
      return <code key={i} className="bg-black/5 rounded px-1 py-0.5 text-xs font-mono">{part.slice(1, -1)}</code>;
    if (part.startsWith("**") && part.endsWith("**"))
      return <strong key={i}>{part.slice(2, -2)}</strong>;
    if (part.startsWith("~~") && part.endsWith("~~"))
      return <s key={i} className="opacity-60">{part.slice(2, -2)}</s>;
    if (part.startsWith("*") && part.endsWith("*"))
      return <em key={i}>{part.slice(1, -1)}</em>;
    return part;
  });
}
