import {useState} from 'react';
import ValidatingInputNumberField from "./ValidatingInputNumberField.tsx";
import {actionLoadedMaze, actionLoadingFailed, actionStartedLoading} from "./state/action.ts";

export default function InputForm({state, dispatch}) {
    const [width, setWidth] = useState(10);
    const [height, setHeight] = useState(10);
    const [id, setId] = useState(null as number);

    const handleSubmit = (e) => {
        e.preventDefault();
        dispatch(actionStartedLoading());
        const url = `https://manuel.friedli.info/labyrinth/create/json?w=${width}&h=${height}&id=${id || ''}`;
        fetch(url)
            .then(response => response.json())
            // .then(result => new Promise(resolve => setTimeout(resolve, 600, result)))
            .then(result => {
                dispatch(actionLoadedMaze(result));
            })
            .catch(reason => {
                console.error("Failed to fetch maze data.", reason);
                dispatch(actionLoadingFailed(reason));
            });
    };
    const validateWidthHeightInput = value => {
        if (isNaN(value) || "" === value || (Math.floor(value) !== Number(value))) {
            return {
                valid: false,
                message: "Must be an integer greater than 1.",
                value
            };
        }
        if (value < 1) {
            return {
                valid: false,
                message: "Must be greater than 1.",
                value
            };
        }
        return {
            valid: true,
            value
        };
    };
    const validateIdInput = value => {
        // FIXME doesn't handle strings with characters correctly (e.g. "asdf" yields an empty value, due to "type=number").
        if (isNaN(value) || ("" !== value && ((Math.floor(value) !== Number(value))))) {
            return {
                valid: false,
                message: "Must be empty or an integer",
                value
            };
        }
        return {
            valid: true,
            value
        }
    };
    return (
        <form onSubmit={handleSubmit}>
            <ValidatingInputNumberField id={"width"}
                                        label={"Width"}
                                        value={width}
                                        constraints={{
                                            min: 2
                                        }}
                                        validatorFn={validateWidthHeightInput}
                                        disabled={state.loading}
                                        onChange={setWidth}
            /><br/>
            <ValidatingInputNumberField id={"height"}
                                        label={"Height"}
                                        value={height}
                                        constraints={{
                                            min: 2
                                        }}
                                        validatorFn={validateWidthHeightInput}
                                        disabled={state.loading}
                                        onChange={setHeight}
            /><br/>
            <ValidatingInputNumberField id={"id"}
                                        label={"ID (optional)"}
                                        value={id}
                                        validatorFn={validateIdInput}
                                        disabled={state.loading}
                                        onChange={setId}
            /><br/>
            <label for="algorithm">Algorithmus:</label>
            <select id={"algorithm"}>
                <option>wilson</option>
                <option>random</option>
            </select><br/>
            <button type={"submit"}
                    disabled={state.loading
                        || isNaN(width)
                        || isNaN(height)
                    }>{state.loading ? "Loading ..." : "Create Maze!"}
            </button>
        </form>
    );
}
