"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { ArrowLeft, ExternalLink, Maximize2, Minimize2, FileCode2, Globe, AlertTriangle, Archive } from "lucide-react";
import { Button } from "@/components/ui/button";
import { fetchPage, getPageContentUrl, checkFrameable, type PageInfo } from "@/lib/api/pages";

function PageViewerContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pageId = searchParams.get("id") ?? "";

  const [page, setPage] = useState<PageInfo | null>(null);
  const [fullscreen, setFullscreen] = useState(false);
  const [iframeBlocked, setIframeBlocked] = useState(false);

  useEffect(() => {
    fetchPage(pageId).then(setPage).catch(() => router.push("/pages"));
  }, [pageId, router]);

  // For URL-type pages: check frameable flag (backend header check)
  useEffect(() => {
    if (!page || page.content_type !== "url") return;

    if (page.frameable === false) {
      setIframeBlocked(true);
      return;
    }

    // If frameable is null (old bookmark, not yet checked), check now
    if (page.frameable === null) {
      checkFrameable(pageId).then((ok) => {
        if (!ok) setIframeBlocked(true);
      });
    }
  }, [page, pageId]);

  if (!page) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-muted-foreground text-xs font-mono uppercase tracking-widest animate-pulse">
          Loading...
        </div>
      </div>
    );
  }

  const isUrl = page.content_type === "url";
  const isBundle = page.content_type === "bundle";
  const contentUrl = isUrl ? page.url! : getPageContentUrl(page);
  const externalUrl = isUrl ? page.url! : getPageContentUrl(page);

  return (
    <div className="flex flex-col h-full bg-background">
      {/* Toolbar */}
      {!fullscreen && (
        <div className="flex items-center justify-between px-6 py-3 border-b border-foreground/5 bg-foreground/[0.02] backdrop-blur-xl shrink-0">
          <div className="flex items-center gap-4">
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9 rounded-full hover:bg-foreground/10"
              onClick={() => router.push("/pages")}
            >
              <ArrowLeft className="w-4 h-4" />
            </Button>
            <div className="flex items-center gap-3">
              {isUrl ? (
                <div className="px-3 py-1 text-[9px] font-black uppercase tracking-[0.15em] rounded-full border bg-violet-500/10 border-violet-500/20 text-violet-400 flex items-center gap-1.5">
                  <Globe className="w-3 h-3" />
                  URL
                </div>
              ) : isBundle ? (
                <div className="px-3 py-1 text-[9px] font-black uppercase tracking-[0.15em] rounded-full border bg-emerald-500/10 border-emerald-500/20 text-emerald-400 flex items-center gap-1.5">
                  <Archive className="w-3 h-3" />
                  BUNDLE
                </div>
              ) : (
                <div className="px-3 py-1 text-[9px] font-black uppercase tracking-[0.15em] rounded-full border bg-sky-500/10 border-sky-500/20 text-sky-400 flex items-center gap-1.5">
                  <FileCode2 className="w-3 h-3" />
                  HTML
                </div>
              )}
              <div>
                <h1 className="text-sm font-black uppercase tracking-widest text-foreground">{page.name}</h1>
                {page.description && (
                  <p className="text-[10px] text-muted-foreground font-mono">{page.description}</p>
                )}
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9 rounded-full hover:bg-foreground/10"
              onClick={() => window.open(externalUrl, "_blank")}
            >
              <ExternalLink className="w-4 h-4" />
            </Button>
            {!iframeBlocked && (
              <Button
                variant="ghost"
                size="icon"
                className="h-9 w-9 rounded-full hover:bg-foreground/10"
                onClick={() => setFullscreen(!fullscreen)}
              >
                <Maximize2 className="w-4 h-4" />
              </Button>
            )}
          </div>
        </div>
      )}

      {/* Fullscreen exit button */}
      {fullscreen && (
        <Button
          variant="ghost"
          size="icon"
          className="fixed top-4 right-4 z-50 h-10 w-10 rounded-full bg-black/60 backdrop-blur-md border border-white/10 hover:bg-black/80 text-white shadow-2xl"
          onClick={() => setFullscreen(false)}
        >
          <Minimize2 className="w-4 h-4" />
        </Button>
      )}

      {/* Blocked iframe fallback */}
      {iframeBlocked && isUrl && (
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center space-y-4 p-8">
            <AlertTriangle className="w-12 h-12 text-amber-400 mx-auto" />
            <p className="text-sm font-bold text-foreground">이 사이트는 임베드를 지원하지 않습니다</p>
            <p className="text-xs text-muted-foreground font-mono">X-Frame-Options 또는 CSP 정책으로 인해 iframe에서 표시할 수 없습니다.</p>
            <Button
              variant="outline"
              className="rounded-none border-foreground/10 font-bold uppercase tracking-widest"
              onClick={() => window.open(page.url!, "_blank")}
            >
              <ExternalLink className="w-4 h-4 mr-2" />
              새 탭에서 직접 열기
            </Button>
          </div>
        </div>
      )}

      {/* iframe */}
      {!iframeBlocked && (
        <iframe
          src={contentUrl}
          className={fullscreen ? "fixed inset-0 z-40 w-full h-full" : "flex-1 w-full"}
          style={{ border: "none", background: "white" }}
          sandbox={isUrl ? "allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation" : "allow-scripts allow-same-origin allow-forms allow-popups"}
          title={page.name}
        />
      )}
    </div>
  );
}

export default function PageViewer() {
  return (
    <Suspense fallback={
      <div className="flex items-center justify-center h-full">
        <div className="text-muted-foreground text-xs font-mono uppercase tracking-widest animate-pulse">
          Loading...
        </div>
      </div>
    }>
      <PageViewerContent />
    </Suspense>
  );
}
