import React, { useContext, useEffect, useState } from "react";
import { AuthContext } from "../../AuthProvider";
import { useNavigate, useParams } from "react-router-dom";
import "katex/dist/katex.min.css";
import "./MarkdownEditor.css";
import PathManager from "../PathManager";
import MarkdownView from "./MarkdownView";
import { useMarkdown, useSaveMarkdown } from "../../utils/markdown-queries";

const MarkdownEditor = () => {
    const { roles } = useContext(AuthContext);
    const navigate = useNavigate();
    const { id } = useParams();
    const [title, setTitle] = useState("");
    const [content, setContent] = useState("");
    const [pathId, setPathId] = useState(1);
    const {data: markdown, isLoading, error} = useMarkdown(id);
    const saveMarkdown = useSaveMarkdown();



    useEffect(() => {
        if(markdown){
            setTitle(markdown.title);
            setContent(markdown.content);
            setPathId(markdown.path_id);
        }
    }, [markdown]);

    const handleSave = () => {
        saveMarkdown.mutate(
            {id, data: {title, content, path_id: pathId}},
            {
                onSuccess: () => {
                    navigate("/");
                },
                onError: () => {
                    alert("Error saving markdown file");
                }
            });
    };


    const hasPermission = roles.includes("admin") || roles.includes("creator");
    if (!hasPermission) {
        return <div className="notification is-danger">Permission Denied</div>;
    }

    if(isLoading)
        return <p>Loading...</p>;

    if(error)
        return <p>{error.message || "Failed to load markdown"}</p>;

    return (
        <div className="container mt-5 markdown-editor-container">
            <h2 className="title is-4">{id ? "Edit Markdown" : "Create Markdown"}</h2>
            <div className="columns">
                {/* Editor Column */}
                <div className="column is-half">
                    <form>
                        {/* Title Field */}
                        <div className="field">
                            <label className="label">Title</label>
                            <div className="control">
                                <input
                                    className="input"
                                    type="text"
                                    placeholder="Enter title"
                                    value={title}
                                    onChange={(e) => setTitle(e.target.value)}
                                />
                            </div>
                        </div>

                        {/* PathManager Field */}
                        <div className="field">
                            <label className="label">Path</label>
                            <PathManager
                                currentPathId={pathId}
                                onPathChange={setPathId}
                            />
                        </div>

                        {/* Content Field */}
                        <div className="field">
                            <label className="label">Content</label>
                            <div className="control">
                                <textarea
                                    style={{ height: "70vh" }}
                                    className="textarea"
                                    placeholder="Enter Markdown content"
                                    value={content}
                                    onChange={(e) => setContent(e.target.value)}
                                ></textarea>
                            </div>
                        </div>

                        {/* Save Button */}
                        <div className="field">
                            <div className="control">
                                <button
                                    className="button is-primary"
                                    type="button"
                                    onClick={handleSave}
                                    disabled={saveMarkdown.isLoading}
                                >
                                    {saveMarkdown.isLoading ? "Saving..." : "Save"}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                {/* Preview Column */}
                <div className="column is-half">
                    <h3 className="subtitle is-5">Preview</h3>
                    <MarkdownView content={content} height='70vh'/>
                </div>
            </div>
        </div>
    );
};

export default MarkdownEditor;