import React from "react";
import ResultBlock from "./ResultBlock";
import type { MCPToolResult } from "../types/mcp";

const ToolResultRenderer: React.FC<{
  result: MCPToolResult;
  rendererCode?: string;
  input?: unknown;
}> = ({ result, rendererCode, input }) => {
  if (!rendererCode) {
    return <ResultBlock result={result} />;
  }

  try {
    const exportMatch = rendererCode.match(/export\s+default\s+(.*)/s);
    if (!exportMatch) {
      throw new Error("Invalid renderer format - no export default found");
    }

    const componentCode = exportMatch[1].trim();
    const componentFunction = new Function(
      "React",
      "input",
      "output",
      `
      const { createElement: h, Fragment } = React;
      const JSXComponent = ${componentCode};
      return JSXComponent(input, output);
      `
    );

    const element = componentFunction(React, input || {}, result);

    // For object results, also show the formatted JSON below the custom renderer
    if (typeof result === "object" && result !== null) {
      return (
        <div>
          {element}
          <div className="mt-3 space-y-3">
            <div>
              <h4 className="text-sm font-medium text-gray-300 mb-2">
                Request
              </h4>
              <ResultBlock result={input || {}} />
            </div>
            <div>
              <h4 className="text-sm font-medium text-gray-300 mb-2">
                Response
              </h4>
              <ResultBlock result={result} />
            </div>
          </div>
        </div>
      );
    }

    return element;
  } catch (error) {
    return (
      <ResultBlock
        error={error instanceof Error ? error.message : "Unknown error"}
        result={result}
      />
    );
  }
};
export default ToolResultRenderer;
