import * as stylex from "@stylexjs/stylex";
import { createElement, memo } from "react";

import { controlColor } from "./theme.stylex";
import { size } from "./tokens.stylex";

// Placeholder for the spinning animation, will be updated later
// Taken from: https://tobiasahlin.com/spinkit
export interface SpinnerProps {
	error?: boolean;
}

const scale = stylex.keyframes({
	"0%": {
		transform: "scale3d(1,1,1)",
	},
	"35%": {
		transform: "scale3d(0,0,1)",
	},
	"70%": {
		transform: "scale3d(1,1,1)",
	},
	"100%": {
		transform: "scale3d(1,1,1)",
	},
});

const styles = stylex.create({
	grid: {
		width: size.px20,
		height: size.px20,
		marginBlock: "100px",
		marginInline: "auto",
	},

	tile: {
		width: "33.3333333%",
		height: "33.3333333%",
		backgroundColor: controlColor.progressMarqueeBackground,

		float: "left",

		animationName: scale,
		animationDuration: "1.3s",
		animationIterationCount: "infinite",
		animationTimingFunction: "ease-in-out",
		animationDelay: {
			default: "0",
			":nth-child(1)": ".2s",
			":nth-child(2)": ".3s",
			":nth-child(3)": ".4s",
			":nth-child(4)": ".1s",
			":nth-child(5)": ".2s",
			":nth-child(6)": ".3s",
			":nth-child(7)": "0s",
			":nth-child(8)": ".1s",
			":nth-child(9)": ".2s",
		},
	},

	error: {
		animationName: null,
		backgroundColor: controlColor.progressErrorBackground,

		transform: {
			":nth-child(4)": "scale3d(.75,.75,1)",
			":nth-child(8)": "scale3d(.75,.75,1)",

			":nth-child(1)": "scale3d(.5,.5,1)",
			":nth-child(5)": "scale3d(.5,.5,1)",
			":nth-child(9)": "scale3d(.5,.5,1)",

			":nth-child(2)": "scale3d(.25,.25,1)",
			":nth-child(6)": "scale3d(.25,.25,1)",

			":nth-child(3)": "scale3d(.15,.15,1)",
		},
	},
});

export default memo(function Spinner({ error }: SpinnerProps) {
	const tile = createElement(
		"div",
		stylex.props(styles.tile, error && styles.error),
	);
	return createElement(
		"div",
		{ ...stylex.props(styles.grid), "aria-busy": "true" },
		[tile, tile, tile, tile, tile, tile, tile, tile, tile],
	);
});
