import React, {useState} from "react";
import { Plus, Trash2 } from "lucide-react";
import {useMarkdownTemplate} from "../../utils/queries/markdown-template-queries";
import { Input, Textarea, Label } from "../ui/input";
import { Button } from "../ui/button";
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 FIELD_BOX = "space-y-2 rounded-md border border-border bg-surface/40 p-4";

const TemplatedEditorComponent = ({ variable, value, namespace, onContentChanged }) => {
    console.log("variable", variable);
    const __namespace = `${variable.name}(${variable.type.base_type})`;

    const renderField = () => {
        switch (variable.type.base_type) {
            case "string":
                return (
                    <div className={FIELD_BOX}>
                        <Label>{__namespace}</Label>
                        <Input
                            type="text"
                            value={value ?? ""}
                            onChange={(e) => onContentChanged(variable.name, e.target.value)}
                        />
                    </div>
                );

            case "markdown":
                return (
                    <div className={FIELD_BOX}>
                        <Label>{__namespace}</Label>
                        <Textarea
                            className="max-h-[10vh] font-mono text-sm"
                            value={value}
                            onChange={(e) => onContentChanged(variable.name, e.target.value)}
                        />
                    </div>
                );

            case "enum":
                return (
                    <div className={FIELD_BOX}>
                        <Label>{__namespace}</Label>
                        <select
                            className={SELECT_CLASS}
                            value={value}
                            onChange={(e) => onContentChanged(variable.name, e.target.value)}
                        >
                            {variable.type.definition.enums.map((item) => (
                                <option key={item} value={item}>{item}</option>
                            ))}
                        </select>
                    </div>
                );

            case "list": {
                const [cache, setCache] = useState(value || []);
                const defaultValue = variable.type.definition.default;

                const addItem = () => {
                    const newCache = [...cache, defaultValue];
                    setCache(newCache);
                    onContentChanged(variable.name, newCache);
                };

                const removeItem = (index) => {
                    const newCache = cache.filter((_, i) => i !== index);
                    setCache(newCache);
                    onContentChanged(variable.name, newCache);
                };

                const onItemChange = (index, val) => {
                    const newCache = [...cache];
                    newCache[index] = val;
                    setCache(newCache);
                    onContentChanged(variable.name, newCache);
                };

                return (
                    <div className={FIELD_BOX}>
                        <Label>{__namespace}</Label>
                        {cache.map((item, idx) => (
                            <div className="flex items-start gap-2" key={idx}>
                                <div className="flex-1">
                                    <TemplatedEditorComponent
                                        variable={{ name: idx, type: variable.type.extend_type }}
                                        value={item}
                                        namespace={__namespace}
                                        onContentChanged={(subKey, subVal) => onItemChange(idx, subVal)}
                                    />
                                </div>
                                <Button
                                    type="button"
                                    variant="destructive"
                                    size="icon"
                                    onClick={() => removeItem(idx)}
                                >
                                    <Trash2 className="h-4 w-4" />
                                </Button>
                            </div>
                        ))}
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={addItem}
                        >
                            <Plus className="h-4 w-4" /> Add
                        </Button>
                    </div>
                );
            }

            case "template": {
                const { data: _template, isFetching: loading } = useMarkdownTemplate(variable.type.definition.template.id);
                if (loading) return <Spinner label="Loading template" />;
                const _parameters = _template.parameters;

                const handleSubChange = (key, val) => {
                    const updated = { ...(value || {}), [key]: val };
                    onContentChanged(variable.name, updated);
                };

                return (
                    <div className={FIELD_BOX}>
                        <Label>{__namespace}</Label>
                        {_parameters.map((param, i) => (
                            <div key={i}>
                                <TemplatedEditorComponent
                                    variable={param}
                                    value={(value || {})[param.name]}
                                    namespace={__namespace}
                                    onContentChanged={handleSubChange}
                                />
                            </div>
                        ))}
                    </div>
                );
            }

            default:
                return null;
        }
    };

    return <>{renderField()}</>;
};

const TemplatedEditor = ({ content, template, onContentChanged, style }) => {
    const tpl = template || {
        parameters: [{ name: "markdown", type: { base_type: "markdown", definition: {} } }],
        layout: "<markdown/>",
        title: "default",
    };

    return (
        <div
            className="flex flex-col overflow-hidden rounded-lg border border-border bg-card"
            style={style}
        >
            <div className="flex-1 space-y-4 overflow-y-auto p-4">
                {tpl.parameters.map((variable, idx) => (
                    <TemplatedEditorComponent
                        key={idx}
                        variable={variable}
                        value={content[variable.name]}
                        namespace={tpl.title}
                        onContentChanged={onContentChanged}
                    />
                ))}
            </div>
        </div>
    );
};

export default TemplatedEditor;
