import { Box, Loader, Stack, Text, ThemeIcon } from "@mantine/core";
import { IconPlugConnectedX } from "@tabler/icons-react";
import { useEffect, useRef, useState } from "react";
import classes from "./dashboard.module.css";

export type DashboardFrameMode = "authed" | "public";

type Props = {
  serveSrc: string;
  mode: DashboardFrameMode;
  title: string;
  reloadKey?: string;
};

const DashboardFrame: React.FC<Props> = ({ serveSrc, mode, title, reloadKey }) => {
  const [state, setState] = useState<"loading" | "ready" | "error">("loading");
  const timeoutRef = useRef<number | null>(null);

  const normalisedSrc = (() => {
    const [path, query] = serveSrc.split("?");
    const withSlash = path.endsWith("/") ? path : `${path}/`;
    return query ? `${withSlash}?${query}` : withSlash;
  })();

  useEffect(() => {
    setState("loading");
    timeoutRef.current = window.setTimeout(() => {
      setState((s) => (s === "loading" ? "error" : s));
    }, 20000);
    return () => {
      if (timeoutRef.current) window.clearTimeout(timeoutRef.current);
    };
  }, [normalisedSrc, reloadKey]);

  return (
    <Box className={classes.frameShell}>
      {state === "loading" && (
        <Stack className={classes.frameOverlay} align="center" gap="xs">
          <Loader size="sm" />
          <Text size="xs" c="dimmed">
            Loading dashboard…
          </Text>
        </Stack>
      )}

      {state === "error" && (
        <Stack className={classes.frameOverlay} align="center" gap="xs">
          <ThemeIcon size={44} radius="xl" variant="light" color="gray">
            <IconPlugConnectedX size={22} />
          </ThemeIcon>
          <Text fw={600} size="sm">
            This dashboard couldn't be loaded
          </Text>
          <Text size="xs" c="dimmed" maw={340} ta="center">
            {mode === "public"
              ? "The link may have expired or been revoked."
              : "It may have been unpublished or removed. Try reloading, or pick another version."}
          </Text>
        </Stack>
      )}

      <iframe
        key={`${normalisedSrc}|${reloadKey ?? ""}`}
        className={classes.frame}
        src={normalisedSrc}
        title={title}
        sandbox="allow-scripts"
        referrerPolicy="no-referrer"
        loading="eager"
        onLoad={() => setState("ready")}
        onError={() => setState("error")}
        style={{ visibility: state === "ready" ? "visible" : "hidden" }}
      />
    </Box>
  );
};

export default DashboardFrame;
