"use client";

import { useParams } from "next/navigation";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { useAnatomy } from "@/components/project/use-anatomy";
import { usePreviewBridge } from "@/components/project/preview-bridge-context";

const SAME_ORIGIN_SANDBOX =
  "allow-scripts allow-forms allow-same-origin allow-popups allow-modals allow-downloads" as const;

function sandboxIframe(src: string, origin: string): boolean {
  if (!src.startsWith("http://") && !src.startsWith("https://")) return true;
  try {
    return origin.length > 0 && new URL(src).origin === origin;
  } catch {
    return true;
  }
}

export default function PreviewTab() {
  const params = useParams();
  const projectId = params.projectId as string;
  const { anatomy, loading } = useAnatomy(projectId, { pollMs: 0 });

  const previews = anatomy?.hosting.previews ?? [];
  const options = previews.filter((p) => p.url);

  const [selectedUrl, setSelectedUrl] = useState<string | null>(null);
  const [iframeSrc, setIframeSrc] = useState<string | null>(null);
  const iframeDomRef = useRef<HTMLIFrameElement | null>(null);
  const bridge = usePreviewBridge();
  const origin = typeof window !== "undefined" ? window.location.origin : "";

  // Auto-select first preview on load
  useEffect(() => {
    if (!selectedUrl && options.length > 0) {
      setSelectedUrl(options[0].url);
    }
  }, [options, selectedUrl]);

  useLayoutEffect(() => {
    setIframeSrc(selectedUrl ?? null);
  }, [selectedUrl]);

  useEffect(() => {
    if (!bridge || !iframeSrc || !iframeDomRef.current) return;
    bridge.registerPreviewIframe(iframeDomRef.current, iframeSrc);
  }, [bridge, iframeSrc]);

  return (
    <div style={canvas}>
      {options.length > 1 && (
        <div style={toolbar}>
          <select
            value={selectedUrl ?? ""}
            onChange={(e) => setSelectedUrl(e.target.value)}
            style={select}
          >
            {options.map((p) => (
              <option key={p.id} value={p.url}>
                {p.name} :{p.port} — {p.state}
                {p.command ? ` (${p.command.slice(0, 60)})` : ""}
              </option>
            ))}
          </select>
        </div>
      )}
      <div style={previewFrame}>
        {loading && !iframeSrc ? (
          <div style={loaderWrap}>
            <Loader2
              className="animate-spin"
              style={{ width: 22, height: 22, color: "#9c9590" }}
            />
          </div>
        ) : iframeSrc ? (
          <iframe
            key={iframeSrc}
            src={iframeSrc}
            title="Preview"
            ref={(el) => {
              iframeDomRef.current = el;
              bridge?.registerPreviewIframe(el, iframeSrc);
            }}
            onLoad={() => bridge?.notifyPreviewIframeLoaded()}
            style={iframeStyle}
            {...(sandboxIframe(iframeSrc, origin)
              ? { sandbox: SAME_ORIGIN_SANDBOX }
              : {})}
          />
        ) : (
          <div style={loaderWrap}>
            <p style={emptyText}>No preview available</p>
          </div>
        )}
      </div>
    </div>
  );
}

const canvas: React.CSSProperties = {
  flex: 1,
  minHeight: 0,
  width: "100%",
  display: "flex",
  flexDirection: "column",
  alignSelf: "stretch",
  boxSizing: "border-box",
  padding: "14px 16px 18px",
  background: "linear-gradient(165deg, #faf8f5 0%, #f4f0ea 42%, #ebe7df 100%)",
};

const toolbar: React.CSSProperties = {
  display: "flex",
  gap: 8,
  marginBottom: 10,
  flexWrap: "wrap",
};

const select: React.CSSProperties = {
  flex: 1,
  maxWidth: 480,
  padding: "6px 10px",
  borderRadius: 8,
  border: "1px solid rgba(26, 26, 26, 0.12)",
  background: "rgba(255,255,255,0.85)",
  fontSize: "0.8rem",
  fontFamily: "inherit",
  color: "#1a1a1a",
};

const previewFrame: React.CSSProperties = {
  flex: 1,
  minHeight: 0,
  display: "flex",
  flexDirection: "column",
  borderRadius: 14,
  overflow: "hidden",
  background: "#fff",
  border: "1px solid rgba(26, 26, 26, 0.07)",
  boxShadow:
    "0 1px 2px rgba(26, 26, 26, 0.04), 0 12px 40px rgba(26, 26, 26, 0.07), inset 0 1px 0 rgba(255, 255, 255, 0.85)",
};

const iframeStyle: React.CSSProperties = {
  flex: 1,
  width: "100%",
  minHeight: 0,
  border: "none",
  background: "#fcfcfb",
  display: "block",
};

const loaderWrap: React.CSSProperties = {
  flex: 1,
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  minHeight: 200,
  background: "#fcfcfb",
};

const emptyText: React.CSSProperties = {
  fontSize: "0.85rem",
  color: "#a09a90",
  fontFamily: '"Outfit", "Inter", ui-sans-serif, sans-serif',
};
