import { useTranslation } from "react-i18next";
import { useLocation, useRoute } from "wouter";
import {
  useGetApp,
  getGetAppQueryKey,
} from "@workspace/api-client-react";
import { ArrowLeft, ArrowRight, ExternalLink } from "lucide-react";

export default function EmbeddedAppPage() {
  const { t, i18n } = useTranslation();
  const lang = i18n.language;
  const isRtl = lang === "ar";
  const [, setLocation] = useLocation();
  const [, params] = useRoute<{ id: string }>("/embedded/:id");
  const idStr = params?.id ?? "";
  const id = Number(idStr);
  const validId = Number.isFinite(id) && id > 0;

  const { data: app, isLoading, error } = useGetApp(id, {
    query: {
      queryKey: getGetAppQueryKey(id),
      enabled: validId,
    },
  });

  const goBack = () => setLocation("/");
  const Back = isRtl ? ArrowRight : ArrowLeft;

  if (!validId) {
    return (
      <div className="min-h-screen flex items-center justify-center os-bg p-6 text-center">
        <div>
          <p className="text-slate-700 mb-3">{t("embeddedFrame.notFound")}</p>
          <button
            onClick={goBack}
            className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-200 bg-white text-sm hover:bg-slate-50"
          >
            <Back size={16} /> {t("embeddedFrame.back")}
          </button>
        </div>
      </div>
    );
  }

  const name = app ? (lang === "ar" ? app.nameAr : app.nameEn) : "";
  const url = app?.externalUrl ?? "";
  // openMode must be external_iframe AND externalUrl must be set; otherwise
  // there's nothing to render — fall back to a friendly notice.
  const canEmbed = !!app && app.openMode === "external_iframe" && !!url;

  return (
    <div className="min-h-screen flex flex-col os-bg" dir={isRtl ? "rtl" : "ltr"}>
      <div
        className="border-b border-slate-200/70 px-3 py-2 flex items-center gap-2 sticky top-0 z-30 bg-white/95 backdrop-blur"
      >
        <button
          onClick={goBack}
          className="p-2 rounded-xl hover:bg-slate-100 text-muted-foreground hover:text-foreground transition-colors"
          aria-label={t("embeddedFrame.back")}
        >
          <Back size={18} />
        </button>
        <h1 className="text-sm font-semibold truncate flex-1">
          {isLoading ? "…" : (name || t("embeddedFrame.title"))}
        </h1>
        {url && (
          <a
            href={url}
            target="_blank"
            rel="noopener noreferrer"
            className="p-2 rounded-xl hover:bg-slate-100 text-muted-foreground hover:text-foreground transition-colors"
            aria-label={t("embeddedFrame.openInNewTab")}
            title={t("embeddedFrame.openInNewTab")}
          >
            <ExternalLink size={16} />
          </a>
        )}
      </div>
      <div className="flex-1 relative">
        {error ? (
          <div className="absolute inset-0 flex items-center justify-center text-sm text-slate-500">
            {t("embeddedFrame.loadError")}
          </div>
        ) : !canEmbed ? (
          <div className="absolute inset-0 flex items-center justify-center text-sm text-slate-500 px-6 text-center">
            {isLoading ? t("common.loading") : t("embeddedFrame.notEmbeddable")}
          </div>
        ) : (
          <iframe
            src={url}
            title={name || t("embeddedFrame.title")}
            className="absolute inset-0 w-full h-full border-0"
            // Permissive sandbox so the embedded site can run scripts and
            // forms while still being isolated from our origin's cookies.
            sandbox="allow-scripts allow-forms allow-popups allow-same-origin allow-downloads"
            referrerPolicy="no-referrer-when-downgrade"
          />
        )}
      </div>
    </div>
  );
}
