import {
    useMarkdownTemplate,
    useMarkdownTemplates,
} from "../../../utils/queries/markdown-template-queries";
import {
    useCreateMarkdownTemplateSetting,
    useMarkdownTemplateSetting,
    useUpdateMarkdownTemplateSetting
} from "../../../utils/queries/markdown-template-setting-queries";
import React, {useEffect, useState} from "react";
import { Plus, Save } from "lucide-react";
import {useUpdateMarkdownSetting} from "../../../utils/queries/markdown-setting-queries";
import { Button } from "../../ui/button";
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 MarkdownTemplateSettingPanel = ({markdownSetting, onClose}) => {
    const {data: setting, isFetching: settingIsFetching } = useMarkdownTemplateSetting(markdownSetting?.template_setting_id);
    const {data: templates, isFetching: templatesAreFetching}=useMarkdownTemplates();
    const {data: template, isFetching: templateIsFetching} = useMarkdownTemplate(setting?.template_id);
    const [selectedTemplateId, setSelectedTemplateId] = useState(template?.id ?? undefined);

    const createMarkdownTemplateSetting = useCreateMarkdownTemplateSetting();
    const updateMarkdownSetting = useUpdateMarkdownSetting();
    const updateMarkdownTemplateSetting = useUpdateMarkdownTemplateSetting();
    const handleCreateTemplateSetting = () => {
        createMarkdownTemplateSetting.mutate({}, {
           onSuccess: (data) => {
               updateMarkdownSetting.mutate({
                   id: markdownSetting.id,
                   data: {
                       template_setting_id: data.id,
                   }
               });
           }
        });
    };

    const handleSaveMarkdownTemplateSetting = () => {
        updateMarkdownTemplateSetting.mutate({
            id: setting.id,
            data: {
                template_id: selectedTemplateId,
            }
        }, {
            onSuccess: () => alert("Saved"),
            onError: () => alert("Failed to save"),
        });
        onClose();
    };

    useEffect(() => {
        if(template?.id && selectedTemplateId === undefined) {
            setSelectedTemplateId(template?.id ?? undefined);
        }
    },[template, selectedTemplateId]);
    if (settingIsFetching || templatesAreFetching || templatesAreFetching || templateIsFetching) {
        return (
            <div className="flex justify-center py-6">
                <Spinner label="Loading template" />
            </div>
        );
    }
    return setting ? (
        <div className="mt-4 space-y-4 rounded-lg border border-border bg-surface/40 p-5">
            <h4 className="font-mono text-sm font-semibold uppercase tracking-wide text-foreground">
                Template Setting
            </h4>
            <div className="space-y-2">
                <Label htmlFor="use-template-select">Use Template</Label>
                <select
                    id="use-template-select"
                    className={SELECT_CLASS}
                    value={selectedTemplateId}
                    onChange={(e) => {
                        setSelectedTemplateId(e.target.value);
                    }}
                >
                    <option value="">(default)</option>
                    {templates.map((_template, index) => (
                        <option key={index} value={_template.id}>{_template.title}</option>
                    ))}

                </select>
            </div>
            <Button
                type="button"
                onClick={handleSaveMarkdownTemplateSetting}
            >
                <Save className="h-4 w-4" /> Save Template Setting
            </Button>
        </div>
    ) : (
        <Button
            type="button"
            onClick={handleCreateTemplateSetting}
        >
            <Plus className="h-4 w-4" /> Create Template Setting
        </Button>
    );
};

export default MarkdownTemplateSettingPanel;