import { Dispatch, Fragment, SetStateAction, useContext, useRef } from "react";
import { ParsedDeploymentServiceConfig } from "@/src/types";
import Select, { TWUISelectOptionObject } from "@/twui/components/form/Select";
import Row from "@/twui/components/layout/Row";
import Button from "@/twui/components/layout/Button";
import Span from "@/twui/components/layout/Span";
import Border from "@/twui/components/elements/Border";
import { X } from "lucide-react";

type Props = {
    service: ParsedDeploymentServiceConfig;
    setLog: Dispatch<SetStateAction<string | undefined>>;
    log?: string;
};

export default function ServiceClusterServerLogSelectorSelectLog({
    service,
    setLog,
    log,
}: Props) {
    const logs = service.logs;

    const log_strings = logs?.map((l) => (typeof l == "string" ? l : l.cmd));
    const is_custom_log =
        log?.match(/./) && !Boolean(log_strings?.find((l) => l == log));

    return (
        <Fragment>
            {is_custom_log ? (
                <Row className="grow">
                    <Border className="w-full py-1 h-[42px]">
                        <Row className="w-full justify-between">
                            <Span>{log}</Span>
                            <Button
                                title="Clear Custom Log"
                                variant="ghost"
                                className="p-1"
                                onClick={() => {
                                    setLog(undefined);
                                }}
                            >
                                <X size={17} />
                            </Button>
                        </Row>
                    </Border>
                </Row>
            ) : (
                <Select
                    options={[
                        ...(log_strings?.map(
                            (l) =>
                                ({
                                    value: l,
                                    title: l,
                                }) as TWUISelectOptionObject,
                        ) || []),
                    ]}
                    changeHandler={(v) => {
                        setLog(v);
                    }}
                />
            )}
        </Fragment>
    );
}
