import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import "katex/dist/katex.min.css";
import "./MarkdownContent.css";
import MarkdownView from "./MarkdownView";
import { useMarkdown } from "../../utils/queries/markdown-queries";
import { useMarkdownSetting } from "../../utils/queries/markdown-setting-queries";
import { useMarkdownTemplate } from "../../utils/queries/markdown-template-queries";
import { useMarkdownTemplateSetting } from "../../utils/queries/markdown-template-setting-queries";
import { useTree } from "../../utils/queries/tree-queries";
import { getMarkdownIdByPath } from "../../utils/pathUtils";
import { parseMarkdownContent } from "../../utils/safe-json";
import { Spinner } from "../ui/misc";

const StandaloneMarkdownPage = () => {
    const location = useLocation();
    const [indexTitle, setIndexTitle] = useState(null);
    const [markdownId, setMarkdownId] = useState(null);
    
    // Extract path from /pg/project/index -> project/index
    const pathString = location.pathname.replace(/^\/pg\//, '');
    
    const { data: tree, isLoading: isTreeLoading } = useTree();
    const { data: markdown, isLoading: isMarkdownLoading, error } = useMarkdown(markdownId);
    const { data: setting, isFetching: isSettingFetching } = useMarkdownSetting(markdown?.setting_id);
    const { data: templateSetting, isFetching: isTemplateSettingFetching } = useMarkdownTemplateSetting(setting?.template_setting_id);
    const { data: template, isFetching: isTemplateFetching } = useMarkdownTemplate(templateSetting?.template_id);

    // Resolve markdown ID from path using tree
    useEffect(() => {
        if (tree && pathString) {
            const resolvedId = getMarkdownIdByPath(tree, pathString);
            setMarkdownId(resolvedId);
        }
    }, [tree, pathString]);

    useEffect(() => {
        if (markdown && markdown.title === "index" && pathString) {
            const pathParts = pathString.split('/').filter(part => part.length > 0);
            
            if (pathParts.length === 0) {
                // Root index: /pg/ or /pg
                setIndexTitle("Home");
            } else {
                // Directory index: /pg/Projects or /pg/Projects/project1
                // Use the last directory name as title
                const directoryName = pathParts[pathParts.length - 1];
                setIndexTitle(directoryName);
            }
        }
    }, [markdown, pathString]);

    const notReady = isTreeLoading || isMarkdownLoading || isSettingFetching || isTemplateSettingFetching || isTemplateFetching;

    if (notReady) {
        return (
            <div className="flex min-h-screen items-center justify-center">
                <Spinner label="Loading" />
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex min-h-screen items-center justify-center px-6">
                <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 font-mono text-sm text-destructive">
                    Error: {error.message || "Failed to load content"}
                </div>
            </div>
        );
    }

    if (!notReady && !markdownId) {
        return (
            <div className="flex min-h-screen items-center justify-center px-6">
                <p className="font-mono text-sm text-muted-foreground">
                    Markdown not found for path:{" "}
                    <span className="text-foreground">{pathString}</span>
                </p>
            </div>
        );
    }

    if (markdown?.isMessage) {
        return (
            <div className="mx-auto max-w-3xl px-6 py-12">
                <div className="rounded-lg border border-primary/30 bg-primary/10 px-5 py-4">
                    <h4 className="mb-1 font-mono text-base font-semibold text-primary">
                        {markdown.title}
                    </h4>
                    <p className="text-sm text-foreground/80">
                        {markdown.content}
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="relative z-10 mx-auto max-w-4xl px-6 py-12">
            <h1 className="mb-8 border-b border-border pb-4 font-mono text-3xl font-bold tracking-tight text-foreground">
                {markdown?.title === "index" ? indexTitle : markdown?.title}
            </h1>
            {markdown && (
                <MarkdownView content={parseMarkdownContent(markdown.content)} template={template} />
            )}
        </div>
    );
};

export default StandaloneMarkdownPage;