import { useCustomControl } from "../contexts/customControlContextFactory.js";

import type { ChangeEvent, FC } from "react";
import "../style/controls/cssMarginInput.scss";

type CssMarginInputValue = [number, number, number, number];

type CssMarginInputParams = {
    dashicon?: string;
};

const REMOVE_LEADING_ZERO_REGEXP = /^0+0/;

const CssMarginInput: FC = () => {
    const {
        value,
        setValue,
        params: { dashicon },
    } = useCustomControl<CssMarginInputValue, CssMarginInputParams>();

    const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
        const inputValue = +e.target.value;
        const newValue = [...value] as CssMarginInputValue;
        newValue.splice(+e.target.dataset.index, 1, inputValue);
        setValue(newValue);
    };

    const createInput = (index: number) => (
        <input
            type="number"
            value={value[index].toString().replace(REMOVE_LEADING_ZERO_REGEXP, "")}
            data-index={index}
            onChange={handleChange}
        />
    );

    return (
        <>
            <div>
                <div></div>
                <div>{createInput(0)}</div>
                <div></div>
            </div>
            <div>
                <div>{createInput(3)}</div>
                <div>
                    <span className={`dashicons dashicons-${dashicon}`}></span>
                </div>
                <div>{createInput(1)}</div>
            </div>
            <div>
                <div></div>
                <div>{createInput(2)}</div>
                <div></div>
            </div>
        </>
    );
};

export { CssMarginInput, type CssMarginInputValue, type CssMarginInputParams };
