import Stack from "@/twui/components/layout/Stack";
import { useContext, useEffect, useRef, useState } from "react";
import { AppContext } from "@/src/pages/_app";
import { TtydInfoObject, WebSocketDataType } from "@/src/types";
import useWebSocketEventHandler from "@/twui/components/hooks/useWebSocketEventHandler";
import _ from "lodash";
import Loading from "@/twui/components/elements/Loading";
import Center from "@/twui/components/layout/Center";
import TtydIframe from "@/src/components/general/ttyd-iframe";
import useStatus from "@/twui/components/hooks/useStatus";

type Props = {
    paradigm: "shell" | "pm2-logs";
};

export default function RelayShellView({ paradigm }: Props) {
    const { pageProps, ws } = useContext(AppContext);
    const { user } = pageProps;

    const username = user.super_admin ? "root" : user.username;
    const cmd =
        paradigm == "pm2-logs"
            ? "pm2 logs"
            : user.super_admin
              ? "bash"
              : username
                ? `su - ${username} -c "bash"`
                : undefined;

    const { data } = useWebSocketEventHandler<WebSocketDataType>();
    const [ttyd, setTtyd] = useState<TtydInfoObject>();

    const { refresh, setRefresh } = useStatus();

    const WsReqSentRef = useRef(false);

    function sendKillPort() {
        if (ttyd?.port) {
            ws.sendData({
                event: "client:kill-port",
                port: ttyd.port,
            });
        }
    }

    useEffect(() => {
        if (!ws?.socket || WsReqSentRef.current) {
            return;
        }

        ws.sendData({
            event:
                paradigm == "pm2-logs"
                    ? "client:relay-pm2-logs"
                    : "client:relay-shell",
            cmd,
        });

        WsReqSentRef.current = true;

        return function () {
            sendKillPort();
        };
    }, [ws, refresh]);

    useEffect(() => {
        if (WsReqSentRef.current) {
            sendKillPort();

            setTtyd(undefined);
            WsReqSentRef.current = false;
            setRefresh((prev) => prev + 1);
        }
    }, []);

    useEffect(() => {
        if (ttyd) return;

        if (
            (paradigm == "shell" &&
                data?.event == "server:relay-shell" &&
                data?.ttyd) ||
            (paradigm == "pm2-logs" &&
                data?.event == "server:relay-pm2-logs" &&
                data?.ttyd)
        ) {
            setTimeout(() => {
                setTtyd(
                    data.ttyd
                        ? {
                              ...data.ttyd,
                              href: `${window.location.origin}${data.ttyd.url}`,
                          }
                        : undefined,
                );
            }, 2000);
        }
    }, [data]);

    const title = paradigm == "pm2-logs" ? `Admin Logs` : `Relay Shell`;

    return (
        <Stack className="gap-0 w-full">
            {ttyd?.url && ttyd.port ? (
                <Stack className="gap-0">
                    <TtydIframe
                        url={ttyd?.url}
                        title={title}
                        wrapperProps={{
                            className: "border-none",
                        }}
                    />
                </Stack>
            ) : (
                <Center className="p-10 h-[460px]">
                    <Loading />
                </Center>
            )}
            <hr />
        </Stack>
    );
}
