import { useState, memo, useCallback, useEffect, useRef } from "react";
import { marked } from "marked";
import type { ChatTurn as ChatTurnType, ChatTurnBlock } from "../lib/api";

interface ChatTurnProps {
  turn: ChatTurnType;
  onUpdate: (turnId: string, updates: Partial<ChatTurnType>) => void;
}

// Configure marked with breaks enabled
marked.setOptions({
  breaks: true,
});

const ChatTurn = memo(function ChatTurn({ turn, onUpdate }: ChatTurnProps) {
  const [thinkingExpanded, setThinkingExpanded] = useState(false);
  const [toolCallsExpanded, setToolCallsExpanded] = useState(true);
  const [renderedBlocks, setRenderedBlocks] = useState<Map<number, string>>(new Map());
  const blocksEndRef = useRef<HTMLDivElement>(null);

  const handleThinkingToggle = useCallback(() => {
    setThinkingExpanded((prev) => !prev);
  }, []);

  const handleToolCallsToggle = useCallback(() => {
    setToolCallsExpanded((prev) => !prev);
  }, []);

  const formatDuration = (ms: number): string => {
    if (ms < 1000) return `${ms}ms`;
    const seconds = (ms / 1000).toFixed(1);
    return `${seconds}s`;
  };

  const formatTokenCount = (count: number): string => {
    if (count >= 1000) {
      return `${(count / 1000).toFixed(1)}k`;
    }
    return count.toString();
  };

  const modelId = turn.llm || "Unknown";
  const modeLabel =
    turn.mode?.charAt(0).toUpperCase() + turn.mode?.slice(1) || "Unknown";
  const statusLabel =
    turn.status?.charAt(0).toUpperCase() + turn.status?.slice(1) || "Unknown";
  const startedAt = new Date(turn.createdAt);

  return (
    <div className="border-b border-border-subtle pb-4 last:border-b-0">
      {/* Turn Header */}
      <div className="flex items-center gap-4 text-xs text-text-muted mb-3 px-4">
        <div>{startedAt.toLocaleTimeString()}</div>
        <div className="flex items-center gap-2">
          <span className="font-mono">{modelId}</span>
        </div>
        <div className="w-px h-3 bg-border-subtle" />
        <div>{modeLabel}</div>
        <div className="w-px h-3 bg-border-subtle" />
        <div
          className={
            turn.status === "finished"
              ? "text-green-500"
              : turn.status === "error"
                ? "text-red-500"
                : "text-yellow-500"
          }
        >
          {statusLabel}
        </div>
        <div className="w-px h-3 bg-border-subtle" />
        {turn.stats && (
          <>
            <div className="w-px h-3 bg-border-subtle" />
            <div>{formatDuration(turn.stats.durationMs)}</div>
            <div className="w-px h-3 bg-border-subtle" />
            <div>
              {turn.stats.inputTokens
                ? formatTokenCount(turn.stats.inputTokens)
                : "0"}{" "}
              in /{" "}
              {turn.stats.responseTokens
                ? formatTokenCount(turn.stats.responseTokens)
                : "0"}{" "}
              out
            </div>
          </>
        )}
      </div>

      {/* Error Alert */}
      {turn.errorMessage && turn.status === "error" && (
        <div className="max-w-[80%] ml-0 mb-4">
          <div className="bg-red-600 text-white rounded p-4 border-2 border-red-400">
            <div className="text-sm font-semibold mb-2 flex items-center gap-2">
              <span>⚠️</span> Error
            </div>
            <div className="whitespace-pre-wrap">{turn.errorMessage}</div>
          </div>
        </div>
      )}

      {/* User Prompt */}
      <div className="max-w-[80%] ml-0 mb-4">
        <div className="bg-[#4a0000] text-white rounded p-4">
          <div className="text-sm font-semibold mb-2">You</div>
          <div className="whitespace-pre-wrap">{turn.prompts?.user || ""}</div>
        </div>
      </div>

      {/* Agent Response */}
      {(turn.blocks && turn.blocks.length > 0) && (
        <div className="max-w-[80%] ml-auto mb-4">
          <div className="bg-bg-tertiary border border-border-default rounded p-4">
            <div className="text-sm font-semibold mb-3 text-text-secondary">
              Gadget
            </div>

            {/* Render blocks in order */}
            {turn.blocks.map((block, idx) => {
              if (block.mode === 'thinking') {
                return (
                  <div key={idx} className="mb-3">
                    <div className="text-xs text-text-muted mb-1 font-mono">
                      Thinking
                    </div>
                    <div
                      className="p-3 bg-bg-secondary rounded text-sm text-text-muted whitespace-pre-wrap font-mono text-xs"
                      dangerouslySetInnerHTML={{ 
                        __html: marked.parse(block.content) as string 
                      }}
                    />
                  </div>
                );
              } else if (block.mode === 'responding') {
                return (
                  <div key={idx} className="mb-3">
                    <div
                      className="text-text-primary"
                      dangerouslySetInnerHTML={{ 
                        __html: marked.parse(block.content) as string 
                      }}
                    />
                  </div>
                );
              } else if (block.mode === 'tool') {
                const toolCall = block.content;
                return (
                  <div key={idx} className="mb-3">
                    <div className="flex items-center gap-2 text-xs font-mono text-text-secondary">
                      <span className="text-brand">●</span>
                      <span>{toolCall.name}</span>
                      {toolCall.response && (
                        <span className="text-green-500">✓</span>
                      )}
                    </div>
                  </div>
                );
              }
              return null;
            })}

            <div className="mt-2 text-xs text-text-muted">
              {startedAt.toLocaleTimeString()}
            </div>
          </div>
        </div>
      )}
    </div>
  );
});

export default ChatTurn;
