import { useState, useEffect } from "react";
import { nodeLabel, useStateStore } from "@/lib/state";
import { Icon } from "./icon";
import { Input } from "./ui/input";
import { AppNode } from "config";

export function Name({
	node,
	disabled,
	editing,
}: {
	node: AppNode;
	disabled?: boolean;
	editing?: boolean;
}): React.ReactNode {
	const { id, data } = node;
	const store = useStateStore();
	const [isEditing, setIsEditing] = useState(false);
	useEffect(() => {
		if (data.label === "") {
			setIsEditing(true);
		}
	}, [data.label, disabled]);
	if (node.type === "github" || node.type === "gateway-https" || node.type === "gateway-tcp") {
		return (
			<div className="w-full flex flex-row gap-1 items-center">
				<Icon node={node} />
				<h4 className="w-full cursor-text select-none hover:outline-solid hover:outline-2 hover:outline-gray-200">
					{nodeLabel(node)}
				</h4>
			</div>
		);
	}
	return (
		<div className="w-full flex flex-row gap-1 items-center">
			<Icon node={node} />
			{isEditing || editing ? (
				<Input
					placeholder="Name"
					className="w-full"
					value={data.label}
					onChange={(e) => store.updateNodeData(id, { label: e.target.value })}
					onBlur={() => {
						if (data.label !== "") {
							setIsEditing(false);
						}
					}}
					disabled={disabled}
				/>
			) : (
				<h4
					className="w-full cursor-text select-none hover:outline-solid hover:outline-2 hover:outline-gray-200"
					onClick={() => setIsEditing(true)}
				>
					{data.label}
				</h4>
			)}
		</div>
	);
}
