"use client";

import { useEffect, useRef, useState } from "react";

import {
  fetchCoursewareRuntimeConfig,
  normalizeCoursewareRuntimeConfig,
} from "~/lib/courseware-runtime";

type Lab3TerminalFrameProps = {
  srcPath?: string;
};

export function Lab3TerminalFrame({ srcPath }: Lab3TerminalFrameProps) {
  const frameRef = useRef<HTMLIFrameElement>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [status, setStatus] = useState<"loading" | "ready" | "error">("loading");
  const [isConfigResolved, setIsConfigResolved] = useState(Boolean(srcPath));
  const [runtimeConfig, setRuntimeConfig] = useState(() => {
    return normalizeCoursewareRuntimeConfig(
      srcPath ? { lab3TerminalUrl: srcPath } : undefined,
    );
  });

  const terminalPath = runtimeConfig.lab3TerminalUrl;

  useEffect(() => {
    let isCancelled = false;

    if (srcPath) {
      setRuntimeConfig(
        normalizeCoursewareRuntimeConfig({ lab3TerminalUrl: srcPath }),
      );
      setIsConfigResolved(true);
      return;
    }

    setIsConfigResolved(false);
    setStatus("loading");

    void fetchCoursewareRuntimeConfig()
      .then((nextConfig) => {
        if (isCancelled) return;
        setRuntimeConfig(nextConfig);
      })
      .catch(() => {
        if (isCancelled) return;
        setRuntimeConfig(normalizeCoursewareRuntimeConfig());
      })
      .finally(() => {
        if (isCancelled) return;
        setIsConfigResolved(true);
      });

    return () => {
      isCancelled = true;
    };
  }, [srcPath]);

  useEffect(() => {
    setStatus("loading");
  }, [terminalPath]);

  function handleFrameLoad() {
    const frame = frameRef.current;

    try {
      const frameDocument = frame?.contentDocument;
      const title = frameDocument?.title ?? "";
      const bodyText = frameDocument?.body?.textContent?.replace(/\s+/g, " ").trim() ?? "";

      if (
        /\b404\b/i.test(title) ||
        /\b404\b/i.test(bodyText) ||
        /This page could not be found/i.test(bodyText)
      ) {
        setStatus("error");
        return;
      }
    } catch {
      // Ignore cross-document reads and treat the frame as successfully loaded.
    }

    setStatus("ready");
  }

  return (
    <>
      <section className="lab3-terminal-inline" data-widget-enhanced="true">
        <div>
          <p className="lab3-terminal-inline__eyebrow">Lab 3 Terminal</p>
          <h3>Use the lab shell directly in your browser</h3>
          <p className="lab3-terminal-inline__lede">
            The terminal is docked to the bottom of the page. Expand it with the
            arrow when you&apos;re ready to log in with a local account that has
            password-based SSH access on this lab host.
          </p>
        </div>

        <div className="lab3-terminal-inline__actions">
          <button
            aria-controls="lab3-terminal-dock-panel"
            aria-expanded={isOpen}
            className="lab3-terminal-inline__button"
            onClick={() => setIsOpen((current) => !current)}
            type="button"
          >
            {isOpen ? "Hide Terminal" : "Open Terminal"}
          </button>

          {isConfigResolved ? (
            <a
              className="lab3-terminal-inline__link"
              href={terminalPath}
              rel="noreferrer"
              target="_blank"
            >
              Open in New Tab
            </a>
          ) : (
            <span className="lab3-terminal-inline__link" aria-live="polite">
              Loading terminal...
            </span>
          )}
        </div>
      </section>

      <section
        className={`lab3-terminal-dock${isOpen ? " is-open" : " is-closed"}`}
        data-widget-enhanced="true"
      >
        <button
          aria-controls="lab3-terminal-dock-panel"
          aria-expanded={isOpen}
          className="lab3-terminal-dock__toggle"
          onClick={() => setIsOpen((current) => !current)}
          type="button"
        >
          <span>Lab 3 Terminal</span>
          <span aria-hidden="true" className="lab3-terminal-dock__toggle-icon">
            {isOpen ? "▾" : "▴"}
          </span>
        </button>

        <div className="lab3-terminal-dock__panel" id="lab3-terminal-dock-panel">
          <div className="lab3-terminal-dock__header">
            <p className="lab3-terminal-dock__lede">
              Sign in with any local account that can SSH into this machine, or
              pop the terminal out into a full tab for more room.
            </p>

            {isConfigResolved ? (
              <a
                className="lab3-terminal-dock__link"
                href={terminalPath}
                rel="noreferrer"
                target="_blank"
              >
                Open in New Tab
              </a>
            ) : null}
          </div>

          <div className="lab3-terminal-dock__frame-shell">
            {isConfigResolved ? (
              <iframe
                className="lab3-terminal-dock__frame"
                loading="lazy"
                onError={() => setStatus("error")}
                onLoad={handleFrameLoad}
                ref={frameRef}
                src={terminalPath}
                title="Lab 3 terminal session"
              />
            ) : (
              <div className="lab3-terminal-dock__frame" aria-hidden="true" />
            )}
          </div>

          {status === "loading" ? (
            <p className="lab3-terminal-dock__status" aria-live="polite">
              {isConfigResolved
                ? "Connecting to the embedded terminal..."
                : "Loading terminal configuration..."}
            </p>
          ) : null}

          {status === "error" ? (
            <p
              className="lab3-terminal-dock__status lab3-terminal-dock__status--warning"
              aria-live="polite"
            >
              The browser terminal service is unavailable right now.
            </p>
          ) : (
            <p className="lab3-terminal-dock__status">
              {isConfigResolved ? (
                <>
                  If the terminal page does not appear, open it in a new tab and
                  confirm the service is reachable at <code>{terminalPath}</code>.
                </>
              ) : (
                "Waiting for terminal settings from the deployment runtime."
              )}
            </p>
          )}
        </div>
      </section>
    </>
  );
}
