import React, { useContext, useEffect, useState } from 'react';
import {
    MDBCard,
    MDBCardBody,
    MDBCardTitle,
    MDBCardText,
    MDBBtn,
} 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 Snippet = ({ id = 0 }) => {
    const { authTokens } = useContext(AuthContext);
    const [ snippet, setSnippet ] = useState(null);
    const [ snippetContent, setSnippetContent ] = useState("");
    const getSnippet = async (id) => {
            const response = await fetch(`http://${process.env.REACT_APP_DOMAIN}/api/snippets/${id}`, {
                method: "GET",
                headers: {
                    "Authorization": `Bearer ${authTokens.access}`,
                }
            });
            const data = await response.json();

            if (response.status === 200) {
                console.log(data)
                setSnippet(data)
                setSnippetContent(data?.content)
            } else {
                console.log(data, authTokens)
            }
        };
    const updateSnippet = async () => {
            console.log(snippet, snippetContent);
            const response = await fetch(`http://${process.env.REACT_APP_DOMAIN}/api/snippets/${id}`, {
                method: "PATCH",
                headers: {
                    "Authorization": `Bearer ${authTokens.access}`,
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({...snippet, "content": snippetContent})
            });
            const data = await response.json();

            if (response.status === 200) {
                alert("Snippet updated!")
            } else {
                alert(`Error updating snippet: ${data}`)
            }
        };

    useEffect(() => {
        getSnippet(id);
    }, []);

    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 snippet ? (
        <>
            <MDBCard>
                <MDBCardBody>
                    <MDBCardTitle>{snippet?.title}</MDBCardTitle>
                </MDBCardBody>
            </MDBCard>
            <div style={{textAlign: "left", height: "80vh"}}>
                <MonacoEditor
                    height="80vh"
                    options={options}
                    value={snippetContent}
                    onChange={setSnippetContent}
                />
                <MDBBtn className="mb-4 w-100" onClick={updateSnippet}>Save</MDBBtn>
            </div>
        </>
    ) : (
        <MDBCard>
            <MDBCardBody>
                <MDBCardTitle>Snippet not found!</MDBCardTitle>
                <MDBCardText>Create your own at New Snippet </MDBCardText>
            </MDBCardBody>
        </MDBCard>
    );
}


export default Snippet;
