"use client";

import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { MessageSquare, SkipForward, ChevronRight, X } from "lucide-react";
import { ChatMessage, ThreadState } from "@/lib/types";
import { formatTimestamp } from "@/lib/utils";
import { McpAppCard } from "@/components/mcp/McpAppCard";

interface MessageProps {
  message: ChatMessage;
  threadState?: ThreadState;
  isActiveThread?: boolean;
  onOpenThread?: (threadId: string) => void;
  onSkipThread?: (threadId: string) => void;
  onDeleteThread?: (threadId: string, parentMessageId: string) => void;
}

export function Message({
  message,
  threadState,
  isActiveThread,
  onOpenThread,
  onSkipThread,
  onDeleteThread,
}: MessageProps) {
  const isUser = message.role === "user";
  const isEmpty = !message.content && !message.mcpApps?.length;
  const isThreadParent = !!message.threadId;

  if (isEmpty) return null;

  // Count thread messages (excluding empty placeholders)
  const threadMessageCount = threadState
    ? threadState.messages.filter((m) => m.content.length > 0).length
    : 0;

  // Whether skip has been used for this thread
  const threadSkipped = threadState?.skipped ?? false;

  return (
    <div className="animate-message-in px-4 py-3 hover:brightness-[1.02] transition-colors group" style={{ borderBottom: "1px solid rgba(255,255,255,0.03)" }}>
      <div className="flex gap-4 max-w-[900px]">
        {/* Avatar */}
        <div className="shrink-0 mt-0.5">
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold"
            style={{
              backgroundColor: isUser ? "#5865f2" : "#ff6d5a",
              color: "#ffffff",
            }}
          >
            {isUser ? "U" : "AI"}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0">
          {/* Header */}
          <div className="flex items-baseline gap-2 mb-0.5">
            <span
              className="text-[15px] font-semibold"
              style={{ color: isUser ? "#ffffff" : "#ff6d5a" }}
            >
              {isUser ? "You" : "LocalBosses AI"}
            </span>
            <span className="text-xs" style={{ color: "#72767d" }}>
              {formatTimestamp(message.timestamp)}
            </span>
          </div>

          {/* Message body */}
          {message.content && (
            <div
              className="prose-chat text-[15px] leading-[1.375rem]"
              style={{ color: "#dcddde" }}
            >
              <ReactMarkdown remarkPlugins={[remarkGfm]}>
                {message.content}
              </ReactMarkdown>
            </div>
          )}

          {/* MCP Apps (non-thread messages) */}
          {message.mcpApps?.map((app) => (
            <McpAppCard
              key={app.id}
              app={app}
              onToolCall={async (name, args) => {
                console.log(`[MCP] Tool call: ${name}`, args);
                return {
                  status: "ok",
                  message: "Tool executed successfully",
                };
              }}
              onContextUpdate={(context) => {
                console.log("[MCP] Context update:", context);
              }}
              onMessageSend={(content) => {
                console.log("[MCP] Message send:", content);
              }}
            />
          ))}

          {/* ─── Thread parent extras ──────────────────────────────── */}
          {isThreadParent && (
            <>
              {/* Skip button (only if not yet skipped and skipLabel exists) */}
              {message.skipLabel && !threadSkipped && (
                <button
                  onClick={() => onSkipThread?.(message.threadId!)}
                  className="mt-2 flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all duration-150 hover:brightness-125"
                  style={{
                    backgroundColor: "rgba(255,109,90,0.1)",
                    color: "#ff6d5a",
                    border: "1px solid rgba(255,109,90,0.2)",
                  }}
                >
                  <SkipForward className="w-3 h-3" />
                  Skip → {message.skipLabel}
                </button>
              )}

              {/* Skipped indicator */}
              {message.skipLabel && threadSkipped && (
                <div
                  className="mt-2 flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs"
                  style={{ color: "#72767d" }}
                >
                  <SkipForward className="w-3 h-3" />
                  Showing {message.skipLabel.toLowerCase()} — refine in thread
                </div>
              )}

              {/* Thread Indicator (Discord-style rectangle) */}
              <ThreadIndicator
                threadId={message.threadId!}
                title={message.threadTitle}
                icon={message.threadIcon}
                messageCount={threadMessageCount}
                isActive={isActiveThread ?? false}
                onClick={() => onOpenThread?.(message.threadId!)}
                onDelete={() => onDeleteThread?.(message.threadId!, message.id)}
              />
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Thread Indicator (Discord-style) ────────────────────────────────────────

function ThreadIndicator({
  threadId,
  title,
  icon,
  messageCount,
  isActive,
  onClick,
  onDelete,
}: {
  threadId: string;
  title?: string;
  icon?: string;
  messageCount: number;
  isActive: boolean;
  onClick: () => void;
  onDelete?: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className="mt-2 flex items-center gap-2.5 px-3 py-2 rounded-lg cursor-pointer transition-all duration-150 select-none group/thread"
      style={{
        backgroundColor: isActive ? "#383c44" : "#2f3136",
        maxWidth: "380px",
        border: isActive
          ? "1px solid rgba(255,109,90,0.3)"
          : "1px solid transparent",
      }}
      onMouseEnter={(e) => {
        if (!isActive) {
          e.currentTarget.style.backgroundColor = "#353840";
        }
      }}
      onMouseLeave={(e) => {
        if (!isActive) {
          e.currentTarget.style.backgroundColor = "#2f3136";
        }
      }}
    >
      <MessageSquare
        className="w-4 h-4 shrink-0"
        style={{ color: "#ff6d5a" }}
      />
      <span
        className="text-[13px] font-semibold truncate"
        style={{ color: "#dcddde" }}
      >
        {icon && <span className="mr-1">{icon}</span>}
        {title || "Thread"}
      </span>
      <span className="text-xs shrink-0" style={{ color: "#96989d" }}>
        {messageCount > 0 ? `${messageCount} messages` : "Click to open"}
      </span>
      {onDelete && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="p-0.5 rounded opacity-0 group-hover/thread:opacity-100 transition-all duration-150 hover:bg-red-500/20 ml-auto"
          style={{ color: "#96989d" }}
          title="Delete thread"
        >
          <X className="w-3.5 h-3.5 hover:text-red-400" style={{ color: "inherit" }} />
        </button>
      )}
      {!onDelete && (
        <ChevronRight
          className="w-3.5 h-3.5 shrink-0 ml-auto opacity-50 group-hover/thread:opacity-100 transition-opacity"
          style={{ color: "#96989d" }}
        />
      )}
    </div>
  );
}
