import React, { useEffect, useState } from "react";
import {Link, useParams} from "react-router-dom";
import "katex/dist/katex.min.css";
import "./MarkdownContent.css";
import MarkdownView from "./MarkdownView";
import PermissionGuard from "../PermissionGuard";
import {useMarkdown} from "../../utils/markdown-queries";
import {usePath} from "../../utils/path-queries";

const MarkdownContent = () => {
    const { id } = useParams();
    const [indexTitle, setIndexTitle] = useState(null);
    const {data: markdown, isLoading, error} = useMarkdown(id);
    const {data: path, isFetching: isPathFetching} = usePath(markdown?.path_id);


    useEffect(() => {
        if(markdown && markdown.title === "index" && path){
            setIndexTitle(path.id === 1 ? "Home" : path.name);
        }
    }, [markdown, path]);


    if (isLoading || isPathFetching) {
        return <div>Loading...</div>;
    }

    if (error) {
        return <div>Error: {error.message || "Failed to load content"}</div>;
    }

    return (
        <div className="markdown-content-container">
            <div className="field has-addons markdown-content-container-header">
                <h1 className="title control">{markdown.title === "index" ? indexTitle : markdown.title}</h1>
                <PermissionGuard rolesRequired={['admin']}>
                    <Link to={`/markdown/edit/${id}`} className="control button is-primary is-light">
                        Edit
                    </Link>
                </PermissionGuard>
            </div>

            <MarkdownView content={markdown.content}/>
        </div>
    );
};

export default MarkdownContent;