import React, { useContext, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    MDBCard,
    MDBCardBody,
    MDBCardTitle,
    MDBCardText,
    MDBBtn,
    MDBInput,
} from 'mdb-react-ui-kit';
import 'mdb-react-ui-kit/dist/css/mdb.min.css';
import "@fortawesome/fontawesome-free/css/all.min.css";
import AuthContext from "../context/AuthContext";
import MonacoEditor from 'react-monaco-editor';

const NewSnippet = () => {
    const { authTokens } = useContext(AuthContext);
    const navigate = useNavigate();

    const [ snippetContent, setSnippetContent ] = useState("");
    const [ snippetTitle, setSnippetTitle ] = useState("");

    const saveSnippet = async () => {
            const response = await fetch(`http://${process.env.REACT_APP_DOMAIN}/api/snippets/`, {
                method: "POST",
                headers: {
                    "Authorization": `Bearer ${authTokens.access}`,
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ "content": snippetContent, "title": snippetTitle })
            });
            const data = await response.json();

            if (response.status === 201) {
                alert("Snippet created!")
                navigate(`/snippet/${data?.id}`)
            } else {
                alert(`Error updating snippet: ${data?.detail}`)
            }
        };

    const options = {
        autoIndent: 'full',
        contextmenu: true,
        fontFamily: 'monospace',
        fontSize: 13,
        lineHeight: 24,
        hideCursorInOverviewRuler: true,
        matchBrackets: 'always',
        minimap: {
            enabled: true,
        },
        scrollbar: {
            horizontalSliderSize: 4,
            verticalSliderSize: 18,
        },
        selectOnLineNumbers: true,
        roundedSelection: false,
        readOnly: false,
        cursorStyle: 'line',
        automaticLayout: true,

    };

    return (
        <>
            <MDBCard>
                <MDBCardBody>
                    <MDBInput type="text" placeholder='Your snippet title..' value={snippetTitle} onChange={(e) => setSnippetTitle(e.target.value)}/>
                </MDBCardBody>
            </MDBCard>
            <div style={{textAlign: "left", height: "80vh"}}>
                <MonacoEditor
                    height="80vh"
                    options={options}
                    value={snippetContent}
                    onChange={setSnippetContent}
                />
                <MDBBtn className="mb-4 w-100" onClick={saveSnippet}>Create</MDBBtn>
            </div>
        </>
    );
}


export default NewSnippet;
