"use client";

import { useRef, useCallback, useEffect, useState, forwardRef, useImperativeHandle } from "react";
import { useMcpBridge } from "@/hooks/useMcpBridge";

interface McpAppFrameProps {
  html?: string;
  url?: string;
  height?: number;
  title?: string;
  onToolCall?: (
    name: string,
    args: Record<string, unknown>
  ) => Promise<unknown>;
  onContextUpdate?: (context: Record<string, unknown>) => void;
  onMessageSend?: (content: string) => void;
}

export const McpAppFrame = forwardRef<HTMLIFrameElement, McpAppFrameProps>(function McpAppFrame({
  html,
  url,
  height = 500,
  title,
  onToolCall,
  onContextUpdate,
  onMessageSend,
}, ref) {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  // Expose iframe element to parent via forwarded ref
  useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement);
  const [loaded, setLoaded] = useState(false);

  const { initialize, isInitialized } = useMcpBridge({
    iframeRef,
    onToolCall,
    onContextUpdate,
    onMessageSend,
  });

  const handleLoad = useCallback(() => {
    setLoaded(true);
    initialize();
  }, [initialize]);

  // Build iframe src — prefer URL, fallback to blob from HTML
  const blobUrl = useRef<string | null>(null);

  useEffect(() => {
    if (html && !url) {
      if (blobUrl.current) URL.revokeObjectURL(blobUrl.current);
      const blob = new Blob([html], { type: "text/html" });
      blobUrl.current = URL.createObjectURL(blob);
    }
    return () => {
      if (blobUrl.current) {
        URL.revokeObjectURL(blobUrl.current);
        blobUrl.current = null;
      }
    };
  }, [html, url]);

  const iframeSrc = url || blobUrl.current || undefined;

  return (
    <div
      className="relative rounded-lg overflow-hidden"
      style={{ border: "1px solid #2f3136" }}
    >
      {/* Loading overlay */}
      {!loaded && (
        <div
          className="absolute inset-0 flex items-center justify-center z-10"
          style={{ backgroundColor: "#1a1d23" }}
        >
          <div className="flex flex-col items-center gap-2">
            <div
              className="w-6 h-6 border-2 border-t-transparent rounded-full animate-spin"
              style={{ borderColor: "#ff6d5a", borderTopColor: "transparent" }}
            />
            <span className="text-xs" style={{ color: "#96989d" }}>
              Loading MCP App...
            </span>
          </div>
        </div>
      )}

      {/* Iframe */}
      <iframe
        ref={iframeRef}
        src={iframeSrc}
        onLoad={handleLoad}
        sandbox="allow-scripts allow-forms allow-popups allow-same-origin"
        style={{
          width: "100%",
          height: `${height}px`,
          border: "none",
          backgroundColor: "#1a1d23",
          display: "block",
        }}
        title={title || "MCP App"}
      />
    </div>
  );
});
