import { useEffect, useState } from "react";
import classNames from "classnames";
import style from "./TriSwitch.module.css";

export interface TriSwitchProps {
    style?: React.CSSProperties;
    option1: string;
    option2: string;
    value: string;
    onChange?: (value: string) => void;
}

export default function TriSwitch(props: TriSwitchProps): React.ReactElement {
    const [selectedOption, setSelectedOption] = useState(props.value);
    const getClassNames = () => {
        return classNames(style.triSwitch);
    };

    useEffect(() => {
        handleOptionClick(props.value);
    }, [props.value]);

    const getHandlerClassNames = () => {
        const classList: classNames.ArgumentArray = [];

        classList.push(style.triSwitchHandler);

        if (selectedOption == props.option1) {
            classList.push(style.triSwitchHandlerOption1);
        } else if (selectedOption == props.option2) {
            classList.push(style.triSwitchHandlerOption2);
        } else {
            classList.push(style.triSwitchHandlerSelected);
        }
        return classNames(classList);
    };

    const getOption1ClassNames = () => {
        const classList: classNames.ArgumentArray = [];

        classList.push(style.triSwitchOption1);

        if (selectedOption == props.option1) {
            classList.push(style.triSwitchOption1Selected);
        } else {
            classList.push(style.triSwitchOption1UnSelected);
        }
        return classNames(classList);
    };

    const getOption2ClassNames = () => {
        const classList: classNames.ArgumentArray = [];

        classList.push(style.triSwitchOption2);

        if (selectedOption == props.option2) {
            classList.push(style.triSwitchOption2Selected);
        } else {
            classList.push(style.triSwitchOption2UnSelected);
        }
        return classNames(classList);
    };

    const handleOptionClick = (option: string) => {
        setSelectedOption(option);

        if (props.onChange) {
            props.onChange(option);
        }
    };

    return (
        <>
            <div className={getClassNames()}>
                <div
                    className={getOption1ClassNames()}
                    onClick={() => handleOptionClick(props.option1)}
                >
                    {props.option1}
                </div>
                <div className={getHandlerClassNames()} onClick={() => handleOptionClick("")}>
                    &nbsp;
                </div>
                <div
                    className={getOption2ClassNames()}
                    onClick={() => handleOptionClick(props.option2)}
                >
                    {props.option2}
                </div>
            </div>
        </>
    );
}
