import { useState } from 'react';
import type { ToolCall, ToolResult } from '@/api/types';
import { linkifyPaths } from '@/lib/linkify-paths';
import { MarkdownRenderer } from './MarkdownRenderer';
import { extractServerName, extractToolName } from '@/lib/tool-utils';

interface McpResponseDisplayProps {
  toolCall: ToolCall;
  toolResult: ToolResult;
}

type DisplayMode = 'plain' | 'markdown' | 'rich';

const URL_REGEX = /https?:\/\/[^\s<>"']+/g;
const IMAGE_EXT_REGEX = /\.(png|jpg|jpeg|gif|webp|svg)(\?.*)?$/i;

function isImageUrl(url: string): boolean {
  return IMAGE_EXT_REGEX.test(url);
}

interface ContentSegment {
  type: 'text' | 'image' | 'link' | 'image_line';
  content: string;
  url?: string;
}

/**
 * Splits tool output into content segments for rich display mode:
 * - Standalone image URLs → <img> tag
 * - Markdown image syntax `![alt](url)` → <img> tag
 * - Standalone non-image URLs → link card
 * - Everything else → text paragraph
 */
function parseRichContent(output: string): ContentSegment[] {
  const segments: ContentSegment[] = [];
  const lines = output.split('\n');

  for (const line of lines) {
    const trimmed = line.trimEnd();

    // Empty line
    if (!trimmed) {
      segments.push({ type: 'text', content: line });
      continue;
    }

    // Markdown image syntax: ![alt](url)
    const inlineImgMatch = trimmed.match(/^!\[.*?\]\((https?:\/\/[^\s)]+)\)$/);
    if (inlineImgMatch) {
      segments.push({ type: 'image', content: '', url: inlineImgMatch[1] });
      continue;
    }

    // Standalone URL
    const urlMatch = trimmed.match(URL_REGEX);
    if (urlMatch && urlMatch[0] === trimmed) {
      const url = urlMatch[0];
      if (isImageUrl(url)) {
        segments.push({ type: 'image', content: '', url });
      } else {
        segments.push({ type: 'link', content: url });
      }
      continue;
    }

    // Inline image URLs on their own line (no markdown, just raw URL)
    const imgMatch = trimmed.match(IMAGE_EXT_REGEX);
    if (imgMatch) {
      const possibleUrl = trimmed.match(URL_REGEX);
      if (possibleUrl && possibleUrl[0].length >= trimmed.length * 0.8) {
        segments.push({ type: 'image', content: '', url: possibleUrl[0] });
        continue;
      }
    }

    // Inline URLs in text — detect and wrap them
    const inlineUrls = trimmed.match(URL_REGEX);
    if (inlineUrls) {
      segments.push({ type: 'text', content: trimmed });
    } else {
      segments.push({ type: 'text', content: line });
    }
  }

  return segments;
}

export function McpResponseDisplay({ toolCall, toolResult }: McpResponseDisplayProps) {
  const [mode, setMode] = useState<DisplayMode>('plain');
  const serverName = extractServerName(toolCall.name);
  const toolDisplayName = extractToolName(toolCall.name) ?? toolCall.name;

  const output =
    typeof toolResult.output === 'string'
      ? toolResult.output
      : JSON.stringify(toolResult.output, null, 2);

  const modes: { key: DisplayMode; label: string }[] = [
    { key: 'plain', label: 'Plain' },
    { key: 'markdown', label: 'MD' },
    { key: 'rich', label: 'Rich' },
  ];

  return (
    <div className="space-y-1.5">
      {/* Server badge + tool name + permission dot */}
      <div className="flex items-center gap-1.5 flex-wrap">
        {serverName && (
          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-mono bg-primary/10 text-primary">
            {serverName}
          </span>
        )}
        <span className="text-[11px] font-mono text-muted-foreground">{toolDisplayName}</span>
        <span
          className="size-2 rounded-full bg-emerald-500 shrink-0"
          aria-label="allowed"
          title="Permission: allowed"
        />
      </div>

      {/* Display mode toggle */}
      <div className="flex items-center gap-0.5">
        {modes.map((m) => (
          <button
            key={m.key}
            type="button"
            onClick={() => setMode(m.key)}
            className={`px-2 py-0.5 text-[10px] font-mono rounded transition-colors ${
              mode === m.key
                ? 'bg-primary/15 text-primary'
                : 'text-muted-foreground/50 hover:text-muted-foreground'
            }`}
          >
            {m.label}
          </button>
        ))}
      </div>

      {/* Content */}
      {mode === 'plain' && (
        <pre className="text-[11px] font-mono whitespace-pre-wrap bg-muted/30 rounded px-2 py-1 max-h-72 overflow-y-auto">
          {toolResult.error ? (
            <span className="text-destructive">{toolResult.error}</span>
          ) : (
            linkifyPaths(output)
          )}
          {toolResult.truncated && (
            <div className="text-muted-foreground/60 mt-1">— output truncated —</div>
          )}
        </pre>
      )}

      {mode === 'markdown' && (
        <div className="text-[13px] bg-muted/30 rounded px-2 py-1 max-h-96 overflow-y-auto">
          {toolResult.error ? (
            <span className="text-destructive">{toolResult.error}</span>
          ) : (
            <MarkdownRenderer content={output} />
          )}
          {toolResult.truncated && (
            <div className="text-muted-foreground/60 mt-1 text-xs">— output truncated —</div>
          )}
        </div>
      )}

      {mode === 'rich' && (
        <div className="bg-muted/30 rounded px-2 py-1 max-h-96 overflow-y-auto space-y-1.5">
          {toolResult.error ? (
            <span className="text-destructive text-[11px]">{toolResult.error}</span>
          ) : (
            parseRichContent(output).map((seg, i) => {
              if (seg.type === 'image') {
                return (
                  <div key={i} className="rounded overflow-hidden">
                    <img
                      src={seg.url}
                      alt="Tool result image"
                      className="max-w-full h-auto rounded"
                      loading="lazy"
                    />
                  </div>
                );
              }
              if (seg.type === 'link') {
                return (
                  <a
                    key={i}
                    href={seg.content}
                    target="_blank"
                    rel="noreferrer"
                    className="block text-[11px] font-mono text-primary underline hover:text-primary/80 bg-muted/20 rounded px-2 py-1.5 break-all"
                  >
                    {seg.content}
                  </a>
                );
              }
              return (
                <p key={i} className="text-[11px] leading-relaxed">
                  {linkifyPaths(seg.content)}
                </p>
              );
            })
          )}
          {toolResult.truncated && (
            <div className="text-muted-foreground/60 mt-1 text-xs">— output truncated —</div>
          )}
        </div>
      )}
    </div>
  );
}
