import * as stylex from "@stylexjs/stylex";
import { type ReactElement, type ReactNode, memo } from "react";

import { color, size } from "./tokens.stylex";

import type { TextBoxProps } from "./TextBox";

export interface TextBoxLabelProps {
	/**
	 * The label to display above the input.
	 *
	 * @remarks The label will be displayed in a <span> inside a <label> component.
	 * 			This means that you cannot use divs or similar elements here. You can check here: https://caninclude.glitch.me
	 * 			Avoid putting interactive stuff in here for the same reason.
	 */
	label: ReactNode;
	error?: string | undefined;
	children: ReactElement<TextBoxProps>;
}

const styles = stylex.create({
	label: {
		display: "flex",
		flexDirection: "column",
		gap: size.px1,
		cursor: "pointer",
		width: "100%",
	},
	row: {
		display: "flex",
		flexWrap: "wrap",
		flexDirection: "row",
		alignItems: "baseline",
		gap: size.px2,
	},
	error: {
		transition: "color 0.2s",
		color: {
			default: color.red150,
			"@starting-style": color.orange150,
		},
		fontSize: "75%",
	},
});

export default memo(function TextBoxLabel({
	label,
	error,
	children,
}: TextBoxLabelProps) {
	return (
		// biome-ignore lint/a11y/noLabelWithoutControl: Control is in the children
		<label {...stylex.props(styles.label)}>
			<span {...stylex.props(styles.row)}>
				<span>{label}</span>
				{
					// TODO: aria support
					!!error && (
						<span {...stylex.props(styles.error)}>{error}</span>
					)
				}
			</span>
			{children}
		</label>
	);
});
