import React, { ComponentProps } from "react";
import { twMerge } from "tailwind-merge";
import MarkdownEditorPreviewComponent from "./MarkdownEditorPreviewComponent";
import MarkdownEditorComponent from "./MarkdownEditorComponent";
import MarkdownEditorSelectorButtons from "./MarkdownEditorSelectorButtons";
import Row from "../../layout/Row";
import Stack from "../../layout/Stack";
import AceEditor from "../../editors/AceEditor";

type Props = {
    value?: string;
    setValue?: React.Dispatch<React.SetStateAction<string>>;
    defaultSideBySide?: boolean;
    changeHandler?: (content: string) => void;
    editorProps?: ComponentProps<typeof AceEditor>;
    maxHeight?: string;
    noToggleButtons?: boolean;
};

export default function MarkdownEditor({
    value: existingValue,
    setValue: setExistingValue,
    defaultSideBySide,
    changeHandler,
    editorProps,
    maxHeight: existingMaxHeight,
    noToggleButtons,
}: Props) {
    const [value, setValue] = React.useState<any>(existingValue || ``);

    const [sideBySide, setSideBySide] = React.useState(
        defaultSideBySide || false
    );
    const [preview, setPreview] = React.useState(false);

    const maxHeight = existingMaxHeight || "600px";

    React.useEffect(() => {
        setExistingValue?.(value);
        changeHandler?.(value);
    }, [value]);

    return (
        <Stack className="w-full items-stretch">
            {!noToggleButtons && (
                <MarkdownEditorSelectorButtons
                    {...{ preview, setPreview, setSideBySide, sideBySide }}
                />
            )}

            {sideBySide ? (
                <Row
                    className={twMerge(
                        `w-full grid xl:grid-cols-2 gap-6 max-h-[${maxHeight}]`,
                        "overflow-auto"
                    )}
                >
                    <MarkdownEditorComponent
                        setValue={setValue}
                        value={value}
                        maxHeight={maxHeight}
                        {...editorProps}
                    />
                    <MarkdownEditorPreviewComponent
                        value={value}
                        maxHeight={maxHeight}
                    />
                </Row>
            ) : (
                <Stack
                    className={twMerge(`w-full max-h-[${maxHeight}] h-full`)}
                >
                    {preview ? (
                        <MarkdownEditorPreviewComponent
                            value={value}
                            maxHeight={maxHeight}
                        />
                    ) : (
                        <MarkdownEditorComponent
                            setValue={setValue}
                            value={value}
                            maxHeight={maxHeight}
                            {...editorProps}
                        />
                    )}
                </Stack>
            )}
        </Stack>
    );
}
