import React from "react";
import Button from "../../layout/Button";
import Border from "../../elements/Border";

type Props = {
    preview: boolean;
    setPreview: React.Dispatch<React.SetStateAction<boolean>>;
    sideBySide: boolean;
    setSideBySide: React.Dispatch<React.SetStateAction<boolean>>;
};

export default function MarkdownEditorSelectorButtons({
    preview,
    setPreview,
    setSideBySide,
    sideBySide,
}: Props) {
    const [ready, setReady] = React.useState(false);

    const defSbsName = "TWUIMarkdownEditorDefaultSideBySide";
    const defPrevName = "TWUIMarkdownEditorDefaultPreview";

    React.useEffect(() => {
        if (!ready) return;

        if (sideBySide) {
            localStorage.setItem(defSbsName, "true");
        } else {
            localStorage.removeItem(defSbsName);
        }

        if (preview) {
            localStorage.setItem(defPrevName, "true");
        } else {
            localStorage.removeItem(defPrevName);
        }
    }, [sideBySide, preview, ready]);

    React.useEffect(() => {
        if (localStorage.getItem(defPrevName)) {
            setPreview(true);
        }
        if (!localStorage.getItem(defSbsName)) {
            setSideBySide(false);
        }

        setTimeout(() => {
            setReady(true);
        }, 200);
    }, []);

    return (
        <Border className="p-1.5">
            <Button
                title="Code"
                size="smaller"
                color={sideBySide ? "gray" : preview ? "gray" : "primary"}
                variant={
                    sideBySide ? "outlined" : preview ? "outlined" : "normal"
                }
                onClick={() => {
                    setSideBySide(false);
                    setPreview(false);
                }}
            >
                Code
            </Button>
            <Button
                title="Preview"
                size="smaller"
                color={sideBySide ? "gray" : preview ? "primary" : "gray"}
                variant={
                    sideBySide ? "outlined" : preview ? "normal" : "outlined"
                }
                onClick={() => {
                    setSideBySide(false);
                    setPreview(true);
                }}
            >
                Preview
            </Button>
            <Button
                title="Side By Side"
                size="smaller"
                color={sideBySide ? "primary" : "gray"}
                variant={sideBySide ? "normal" : "outlined"}
                onClick={() => {
                    setSideBySide(true);
                }}
            >
                Side By Side
            </Button>
        </Border>
    );
}
