import Stack from "@/twui/components/layout/Stack";
import { ComponentProps, RefObject, useContext, useRef, useState } from "react";
import { AppContext } from "@/src/pages/_app";
import {
    NormalizedServerObject,
    ParsedDeploymentServiceConfig,
} from "@/src/types/turboci";
import useIntersectionObserver from "@/twui/components/hooks/useIntersectionObserver";
import Center from "@/twui/components/layout/Center";
import Loading from "@/twui/components/elements/Loading";
import ServiceClusterServerViews from "./cluster-server-views";
import Row from "@/twui/components/layout/Row";
import Button from "@/twui/components/layout/Button";
import ServiceClusterServerLogSelector from "./cluster-server-log-selector";
import { twMerge } from "tailwind-merge";
import { ServerTerminalTargets } from "@/src/types";

type Props = {
    service: ParsedDeploymentServiceConfig;
    server: NormalizedServerObject;
    wrapperProps?: ComponentProps<typeof Stack>;
    portRef?: RefObject<number | undefined>;
};

export default function ServiceClusterServer({
    service,
    server,
    wrapperProps,
    portRef,
}: Props) {
    const { pageProps } = useContext(AppContext);

    const elementRef = useRef<HTMLDivElement>(undefined);
    const { isIntersecting } = useIntersectionObserver({ elementRef });

    let service_logs = service.logs;

    if (service.type == "load_balancer") {
        if (!service_logs?.[0]) {
            service_logs = [];
        }

        service_logs.push(
            ...[
                `tail -f /var/log/nginx/access.log`,
                `tail -f /var/log/nginx/error.log`,
            ],
        );
    }

    const [target, setTarget] = useState<
        (typeof ServerTerminalTargets)[number]["name"]
    >(service_logs?.[0] ? "logs" : "shell");

    const first_log = service_logs?.[0];
    const intial_logs =
        typeof first_log == "string" ? first_log : first_log?.cmd;

    const [log, setLog] = useState<string | undefined>(intial_logs);

    return (
        <Stack
            {...wrapperProps}
            className={twMerge("gap-0", wrapperProps?.className)}
        >
            <Row className="w-full justify-between p-4 -mb-6">
                <Row>
                    <code>{server.private_ip}</code>
                    {server.public_ip ? <code>{server.public_ip}</code> : null}
                </Row>

                <Row className="">
                    {ServerTerminalTargets.map((targ, index) => {
                        const is_active = targ.name == target;

                        return (
                            <Button
                                title={`${targ.name}`}
                                onClick={() => {
                                    setTarget(targ.name);
                                }}
                                size="smaller"
                                color="gray"
                                variant={is_active ? undefined : "outlined"}
                                key={index}
                            >
                                {targ.name}
                            </Button>
                        );
                    })}
                </Row>
            </Row>
            {target == "logs" ? (
                <ServiceClusterServerLogSelector
                    {...{ server, service, setLog, log }}
                />
            ) : (
                <Row className="h-[74px]"></Row>
            )}
            <hr />
            <ServiceClusterServerViews
                {...{ server, service, target, portRef }}
                log_cmd={log}
            />
            {/* {isIntersecting ? (
                <ServiceClusterServerViews
                    {...{ server, service, target, log }}
                />
            ) : (
                <Center>
                    <Loading />
                </Center>
            )} */}
        </Stack>
    );
}
