"use client"

import { useEffect, useMemo, useRef } from "react"
import type { AiChatContext } from "@/lib/ai/chat-context"
import { buildEmbedSearchParams } from "@/lib/ai/chat-context"
import { buildAiEmbedUrl, resolveAiEmbedOrigin } from "@/lib/ai/embed-url"
import {
  useAiIframeExternalLinks,
  useAiIframeNavigation,
} from "@/lib/ai/use-ai-iframe-navigation"
import { useTheme } from "next-themes"

type AiChatIframeProps = {
  publicPath?: string
  context: AiChatContext
  className?: string
}

export function AiChatIframe({ publicPath = "/ai", context, className }: AiChatIframeProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null)
  const { resolvedTheme } = useTheme()
  const embedOrigin = useMemo(() => resolveAiEmbedOrigin(publicPath), [publicPath])
  const src = useMemo(() => {
    const qs = buildEmbedSearchParams(context)
    return buildAiEmbedUrl(publicPath, qs)
  }, [publicPath, context])

  useAiIframeNavigation(iframeRef, publicPath)
  useAiIframeExternalLinks(embedOrigin)

  useEffect(() => {
    const iframe = iframeRef.current
    if (!iframe?.contentWindow || !embedOrigin) return
    iframe.contentWindow.postMessage(
      { type: "ULTI_THEME", theme: resolvedTheme === "dark" ? "dark" : "light" },
      embedOrigin
    )
  }, [resolvedTheme, embedOrigin])

  useEffect(() => {
    const iframe = iframeRef.current
    if (!iframe?.contentWindow || !embedOrigin) return
    iframe.contentWindow.postMessage(
      {
        type: "ULTI_CONTEXT_UPDATE",
        context,
        systemPrompt: context.systemPromptExtra,
      },
      embedOrigin
    )
  }, [context, embedOrigin])

  return (
    <iframe
      ref={iframeRef}
      title="UltiAI"
      src={src}
      className={className}
      sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"
      allow="clipboard-read; clipboard-write"
    />
  )
}
