import { NodeType, useNodeMessages } from "@/lib/state";
import { Icon } from "./icon";
import { useEffect, useState } from "react";

export type Props = {
    id: string;
    selected?: boolean;
    children: any;
    type: NodeType;
    state: string | null;
};

export function NodeRect(p: Props) {
    const { id, selected, children, state } = p;
    const messages = useNodeMessages(id);
    const hasFatal = messages.some((m) => m.type === "FATAL");
    const hasWarning = messages.some((m) => m.type === "WARNING");
    const [classes, setClasses] = useState<string[]>([]);
    useEffect(() => {
        const classes = ["px-4", "py-2", "rounded-md"];
        if (hasFatal) {
            classes.push("border-red-500");
        } else if (hasWarning) {
            classes.push("border-yellow-500");
        } else {
            classes.push("border-black");
        }
        if (selected) {
            classes.push("border-2");
        } else {
            classes.push("border");
        }
        if (state === "processing") {
            classes.push("animate-pulse");
        } else if (state === "success") {
            classes.push("bg-green-500");
        } else if (state === "failure") {
            classes.push("bg-red-500");
        } else {
            classes.push("bg-white");
        }
        setClasses(classes);
    }, [selected, hasFatal, hasWarning, state, setClasses]);
    return (
        <div className={classes.join(" ")}>
            <div style={{ position: "absolute", top: "5px", left: "5px" }}>
                {Icon(p.type)}
            </div>
            {children}
        </div>
    )

}
