import React, { useEffect, useState } from "react";
import { useMarkdownTemplates } from "../../utils/queries/markdown-template-queries";
import { Label } from "../ui/input";
import { Spinner } from "../ui/misc";

const SELECT_CLASS =
    "flex h-9 w-full rounded-md border border-input bg-background/60 px-3 py-1 text-sm text-foreground transition-colors focus-visible:outline-none focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring/40";

const TemplateSelector = ({ template, onChange, onCreate }) => {
    const { data: templates, isFetching: templatesAreFetching } = useMarkdownTemplates();
    const [_template, setTemplate] = useState(
        templates?.find((t) => t.id === template?.id) || {
            title: "",
            parameters: [],
            layout: "",
        }
    );

    useEffect(() => {
        setTemplate(
            templates?.find((t) => t.id === template?.id) || {
                title: "",
                parameters: [],
                layout: "",
            }
        );
    }, [template, templates]);

    if (templatesAreFetching) {
        return <Spinner label="Loading templates" />;
    }

    return (
        <div className="space-y-2">
            <Label htmlFor="template-selector">Select Template</Label>
            <select
                id="template-selector"
                className={SELECT_CLASS}
                value={template?.id || ""}
                onChange={(e) => {
                    const id = parseInt(e.target.value, 10);
                    const selectedTemplate = templates.find((t) => t.id === id) || {
                        title: "",
                        parameters: [],
                        layout: "",
                    };
                    onChange(selectedTemplate);
                    if (onCreate) {
                        onCreate(selectedTemplate);
                    }
                }}
            >
                <option value="">(None)</option>
                {templates.map((tmpl) => (
                    <option key={tmpl.id} value={tmpl.id}>
                        {tmpl.title}
                    </option>
                ))}
            </select>
        </div>
    );
};

export default TemplateSelector;
