import React, {useContext, useEffect, useState} from "react";
import { AuthContext } from "../../AuthProvider";
import { useNavigate, useParams } from "react-router-dom";
import { Save } from "lucide-react";
import { useMarkdownTemplate, useSaveMarkdownTemplate } from "../../utils/queries/markdown-template-queries";
import LayoutEditor from "./LayoutEditor";
import ParametersManager from "./ParametersManager";
import { Input, Label } from "../ui/input";
import { Button } from "../ui/button";
import { Spinner } from "../ui/misc";

const MarkdownTemplateEditor = () => {


    const navigate = useNavigate();
    const { strId } = useParams();
    const id = Number(strId);
    const { data: template, isFetching: templateIsFetching } = useMarkdownTemplate(id);
    const saveMarkdownTemplate = useSaveMarkdownTemplate();

    const [title, setTitle] = useState(template?.id || "");
    const [parameters, setParameters] = useState(template?.parameters || []);
    const [layout, setLayout] = useState(template?.layout || "");
    const { roles } = useContext(AuthContext);

    useEffect(() => {
        setTitle(template?.title || "");
        setParameters(template?.parameters || []);
        setLayout(template?.layout || "");
    }, [template]);

    if (templateIsFetching) {
        return (
            <div className="flex justify-center py-20">
                <Spinner label="Loading template" />
            </div>
        );
    }

    if (!roles.includes("admin") || roles.includes("creator"))
        return (
            <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 font-mono text-sm text-destructive">
                Permission Denied
            </div>
        );
    const handleSave = () => {
        saveMarkdownTemplate.mutate(
            { id, data: { title, parameters, layout } },
            {
                onSuccess: () => {
                    navigate("/");
                },
                onError: () => {
                    alert("Error saving template.");
                }
            }
        );
    };

    return (
        <section className="mx-auto max-w-6xl px-6 py-8">
            <h2 className="mb-6 font-mono text-2xl font-bold tracking-tight text-foreground">
                Markdown Template Editor
            </h2>
            <div className="mb-6 space-y-2">
                <Label htmlFor="template-title">Title</Label>
                <Input
                    id="template-title"
                    type="text"
                    placeholder="Enter template title"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                />
            </div>
            <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
                <div className="space-y-3">
                    <h3 className="font-mono text-sm font-semibold uppercase tracking-wide text-foreground">
                        Layout
                    </h3>
                    <div className="rounded-lg border border-border bg-card p-4">
                        <LayoutEditor
                            layout={layout}
                            parameters={parameters}
                            onChange={(newLayout) => setLayout(newLayout)}
                        />
                    </div>
                </div>
                <div className="space-y-3">
                    <h3 className="font-mono text-sm font-semibold uppercase tracking-wide text-foreground">
                        Parameters
                    </h3>
                    <ParametersManager
                        parameters={parameters}
                        onChange={(newParameters) => setParameters(newParameters)}
                    />
                </div>
            </div>
            <div className="mt-6">
                <Button onClick={handleSave}>
                    <Save className="h-4 w-4" /> Save Template
                </Button>
            </div>
        </section>
    );
};

export default MarkdownTemplateEditor;
