import React, { useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";

const PROVIDER_FALLBACKS = [
    { id: "auto", label: "Auto (any configured provider)" },
    { id: "openai", label: "OpenAI" },
    { id: "google", label: "Google Gemini" },
    { id: "anthropic", label: "Anthropic Claude" },
];

function AbilityBadge({ label }) {
    return (
        <span className="aah-text-[10px] aah-rounded-full aah-bg-slate-100 aah-text-slate-700 aah-px-2 aah-py-0.5">
            {label}
        </span>
    );
}

function MetaBoxApp() {
    const [providers, setProviders] = useState(PROVIDER_FALLBACKS);
    const [providersLoading, setProvidersLoading] = useState(true);
    const [selectedProvider, setSelectedProvider] = useState("auto");

    const [abilities, setAbilities] = useState([]);
    const [abilitiesLoading, setAbilitiesLoading] = useState(true);
    const [abilitySearch, setAbilitySearch] = useState("");
    const [selectedAbilities, setSelectedAbilities] = useState([]);

    const [promptDraft, setPromptDraft] = useState("");
    const [workflowResults, setWorkflowResults] = useState(null);
    const [runningWorkflow, setRunningWorkflow] = useState(false);

    const [workflows, setWorkflows] = useState([]);
    const [workflowName, setWorkflowName] = useState("");
    const [savingWorkflow, setSavingWorkflow] = useState(false);
    const [loadingWorkflows, setLoadingWorkflows] = useState(false);

    const postId = aahPostMetaBoxConfig.postId;

    useEffect(() => {
        const fetchProviders = async () => {
            try {
                const res = await fetch(aahPostMetaBoxConfig.providersRestUrl, {
                    headers: {
                        "X-WP-Nonce": aahPostMetaBoxConfig.wpNonce,
                    },
                });
                if (!res.ok) {
                    throw new Error("Failed to load providers");
                }
                const data = await res.json();
                if (data.providers && Array.isArray(data.providers)) {
                    setProviders(
                        data.providers.map((p) => ({
                            id: p.id,
                            label: p.label,
                            supported: p.supported,
                        }))
                    );

                    const auto = data.providers.find((p) => p.id === "auto");
                    if (auto && auto.supported) {
                        setSelectedProvider("auto");
                    }
                }
            } catch (e) {
                console.error(e);
            } finally {
                setProvidersLoading(false);
            }
        };

        const fetchAbilities = async () => {
            if (!aahPostMetaBoxConfig.abilitiesRestUrl) {
                setAbilitiesLoading(false);
                return;
            }
            try {
                setAbilitiesLoading(true);
                const res = await fetch(aahPostMetaBoxConfig.abilitiesRestUrl, {
                    headers: {
                        "X-WP-Nonce": aahPostMetaBoxConfig.wpNonce,
                    },
                });
                const data = await res.json();
                if (data.abilities && Array.isArray(data.abilities)) {
                    setAbilities(data.abilities);
                }
            } catch (e) {
                console.error(e);
            } finally {
                setAbilitiesLoading(false);
            }
        };

        const fetchWorkflows = async () => {
            if (!aahPostMetaBoxConfig.workflowsRestUrl) return;
            try {
                setLoadingWorkflows(true);
                const res = await fetch(aahPostMetaBoxConfig.workflowsRestUrl, {
                    headers: {
                        "X-WP-Nonce": aahPostMetaBoxConfig.wpNonce,
                    },
                });
                const data = await res.json();
                if (data.workflows && Array.isArray(data.workflows)) {
                    setWorkflows(data.workflows);
                }
            } catch (e) {
                console.error(e);
            } finally {
                setLoadingWorkflows(false);
            }
        };

        fetchProviders();
        fetchAbilities();
        fetchWorkflows();
    }, []);

    useEffect(() => {
        const nextPrompt = buildPromptPreview(selectedAbilities, abilities, postId);
        setPromptDraft(nextPrompt);
    }, [selectedAbilities, abilities]);

    const filteredAbilities = useMemo(() => {
        const search = abilitySearch.trim().toLowerCase();
        if (!search) return abilities;
        return abilities.filter((ability) => {
            return [ability.label, ability.description, ability.id]
                .map((item) => (item || "").toLowerCase())
                .some((text) => text.includes(search));
        });
    }, [abilities, abilitySearch]);

    const selectedAbilityObjects = useMemo(
        () =>
            selectedAbilities
                .map((id) => abilities.find((ability) => ability.id === id))
                .filter(Boolean),
        [selectedAbilities, abilities]
    );

    const toggleAbility = (id) => {
        setSelectedAbilities((prev) =>
            prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
        );
    };

    const runWorkflow = async () => {
        if (!postId) {
            alert("Invalid post ID.");
            return;
        }

        if (selectedAbilities.length === 0) {
            alert("Select at least one ability to run.");
            return;
        }

        setRunningWorkflow(true);
        setWorkflowResults(null);

        try {
            const res = await fetch(`${aahPostMetaBoxConfig.restUrl}/content/run-workflow`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-WP-Nonce": aahPostMetaBoxConfig.wpNonce,
                },
                body: JSON.stringify({
                    post_id: postId,
                    abilities: selectedAbilities,
                    prompt: promptDraft,
                    provider: selectedProvider,
                }),
            });

            if (!res.ok) {
                const err = await res.json().catch(() => ({}));
                throw new Error(err.message || "Workflow run failed");
            }

            const data = await res.json();
            setWorkflowResults(data);
            if (!promptDraft && data.prompt) {
                setPromptDraft(data.prompt);
            }
        } catch (e) {
            console.error(e);
            alert(e.message || "Workflow run failed.");
        } finally {
            setRunningWorkflow(false);
        }
    };

    const saveWorkflow = async () => {
        if (!workflowName.trim()) {
            alert("Provide a workflow name before saving.");
            return;
        }
        if (selectedAbilities.length === 0) {
            alert("Select at least one ability.");
            return;
        }
        try {
            setSavingWorkflow(true);
            const res = await fetch(aahPostMetaBoxConfig.workflowsRestUrl, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-WP-Nonce": aahPostMetaBoxConfig.wpNonce,
                },
                body: JSON.stringify({
                    name: workflowName,
                    abilities: selectedAbilities,
                    prompt: promptDraft,
                }),
            });

            if (!res.ok) {
                const err = await res.json().catch(() => ({}));
                throw new Error(err.message || "Unable to save workflow");
            }

            const data = await res.json();
            if (data.workflow) {
                setWorkflows((prev) => [...prev, data.workflow]);
                setWorkflowName("");
            }
        } catch (e) {
            console.error(e);
            alert(e.message || "Unable to save workflow.");
        } finally {
            setSavingWorkflow(false);
        }
    };

    const loadWorkflow = (workflow) => {
        setSelectedAbilities(workflow.abilities || []);
        setPromptDraft(workflow.prompt || buildPromptPreview(workflow.abilities || [], abilities, postId));
    };

    const removeSelected = (id) => {
        setSelectedAbilities((prev) => prev.filter((item) => item !== id));
    };

    return (
        <div className="aah-space-y-3 aah-text-[12px] aah-text-slate-900">
            <div className="aah-space-y-1">
                <label className="aah-block aah-font-medium">AI Agent / Provider</label>
                <select
                    value={selectedProvider}
                    onChange={(e) => setSelectedProvider(e.target.value)}
                    className="aah-block aah-w-full aah-rounded-md aah-border aah-border-slate-300 aah-bg-white aah-px-2 aah-py-1"
                >
                    {providers.map((p) => (
                        <option key={p.id} value={p.id}>
                            {p.label}
                            {p.supported === false && p.id !== "auto" ? " (not configured)" : ""}
                        </option>
                    ))}
                </select>
                {providersLoading && (
                    <p className="aah-text-[11px] aah-text-slate-500">Checking configured providers…</p>
                )}
            </div>

            <div className="aah-space-y-2">
                <div className="aah-flex aah-items-center aah-justify-between aah-gap-2">
                    <label className="aah-font-semibold">Select Abilities</label>
                    <input
                        type="search"
                        placeholder="Search abilities…"
                        value={abilitySearch}
                        onChange={(e) => setAbilitySearch(e.target.value)}
                        className="aah-flex-1 aah-rounded-md aah-border aah-border-slate-300 aah-bg-white aah-px-2 aah-py-1"
                    />
                </div>
                {abilitiesLoading ? (
                    <p className="aah-text-[11px] aah-text-slate-500">Loading abilities…</p>
                ) : (
                    <div className="aah-max-h-48 aah-overflow-y-auto aah-space-y-2">
                        {filteredAbilities.map((ability) => (
                            <label
                                key={ability.id}
                                className="aah-flex aah-gap-2 aah-items-start aah-rounded-md aah-border aah-border-slate-200 aah-bg-white aah-p-2 hover:aah-border-slate-300"
                            >
                                <input
                                    type="checkbox"
                                    checked={selectedAbilities.includes(ability.id)}
                                    onChange={() => toggleAbility(ability.id)}
                                    className="aah-mt-1"
                                />
                                <div>
                                    <div className="aah-flex aah-gap-2 aah-items-center">
                                        <span className="aah-font-semibold">{ability.label}</span>
                                        <AbilityBadge label={ability.module || "module"} />
                                    </div>
                                    <p className="aah-text-[11px] aah-text-slate-600">{ability.description}</p>
                                </div>
                            </label>
                        ))}
                    </div>
                )}
            </div>

            {selectedAbilityObjects.length > 0 && (
                <div className="aah-space-y-2">
                    <div className="aah-flex aah-items-center aah-justify-between">
                        <span className="aah-font-semibold">Selected abilities</span>
                        <span className="aah-text-[11px] aah-text-slate-500">{selectedAbilityObjects.length} selected</span>
                    </div>
                    <div className="aah-flex aah-flex-wrap aah-gap-1">
                        {selectedAbilityObjects.map((ability) => (
                            <span
                                key={ability.id}
                                className="aah-inline-flex aah-items-center aah-gap-1 aah-rounded-full aah-bg-emerald-50 aah-text-emerald-800 aah-border aah-border-emerald-100 aah-px-2 aah-py-1"
                            >
                                {ability.label}
                                <button
                                    type="button"
                                    onClick={() => removeSelected(ability.id)}
                                    className="aah-text-[10px] aah-text-emerald-800 hover:aah-text-emerald-900"
                                >
                                    ✕
                                </button>
                            </span>
                        ))}
                    </div>
                </div>
            )}

            <div className="aah-space-y-1">
                <label className="aah-font-semibold">Prompt preview (editable)</label>
                <textarea
                    value={promptDraft}
                    onChange={(e) => setPromptDraft(e.target.value)}
                    rows={5}
                    className="aah-w-full aah-rounded-md aah-border aah-border-slate-300 aah-bg-white aah-px-2 aah-py-1 aah-text-[12px]"
                />
                <p className="aah-text-[11px] aah-text-slate-500">
                    We build the prompt from your selected abilities. Tweak it before running the workflow.
                </p>
            </div>

            <div className="aah-flex aah-flex-wrap aah-gap-2">
                <button
                    type="button"
                    className="aah-flex-1 aah-inline-flex aah-items-center aah-justify-center aah-rounded-md aah-bg-slate-900 aah-text-white aah-px-2 aah-py-1.5 aah-text-[12px] aah-font-medium disabled:aah-opacity-60 disabled:aah-cursor-not-allowed"
                    onClick={runWorkflow}
                    disabled={runningWorkflow}
                >
                    {runningWorkflow ? "Running abilities…" : "Run abilities"}
                </button>
                <button
                    type="button"
                    className="aah-inline-flex aah-items-center aah-justify-center aah-rounded-md aah-border aah-border-slate-200 aah-bg-white aah-px-2 aah-py-1.5 aah-text-[12px] aah-font-medium disabled:aah-opacity-60 disabled:aah-cursor-not-allowed"
                    onClick={saveWorkflow}
                    disabled={savingWorkflow}
                >
                    {savingWorkflow ? "Saving…" : "Save as workflow"}
                </button>
                <input
                    type="text"
                    placeholder="Workflow name"
                    value={workflowName}
                    onChange={(e) => setWorkflowName(e.target.value)}
                    className="aah-flex-1 aah-rounded-md aah-border aah-border-slate-200 aah-bg-white aah-px-2 aah-py-1"
                />
            </div>

            <div className="aah-space-y-2 aah-border-t aah-border-slate-200 aah-pt-2">
                <div className="aah-flex aah-items-center aah-justify-between">
                    <span className="aah-font-semibold">Saved workflows</span>
                    {loadingWorkflows && (
                        <span className="aah-text-[11px] aah-text-slate-500">Loading…</span>
                    )}
                </div>
                {workflows.length === 0 && !loadingWorkflows && (
                    <p className="aah-text-[11px] aah-text-slate-500">No workflows saved yet.</p>
                )}
                <div className="aah-space-y-2">
                    {workflows.map((workflow) => (
                        <div
                            key={workflow.id}
                            className="aah-rounded-md aah-border aah-border-slate-200 aah-bg-slate-50 aah-p-2 aah-space-y-1"
                        >
                            <div className="aah-flex aah-items-center aah-justify-between">
                                <div>
                                    <div className="aah-font-semibold">{workflow.name}</div>
                                    <div className="aah-text-[11px] aah-text-slate-500">
                                        {workflow.abilities?.length || 0} abilities
                                    </div>
                                </div>
                                <div className="aah-flex aah-gap-1">
                                    <button
                                        type="button"
                                        className="aah-text-[11px] aah-rounded-full aah-bg-white aah-border aah-border-slate-200 aah-px-2 aah-py-1"
                                        onClick={() => loadWorkflow(workflow)}
                                    >
                                        Load
                                    </button>
                                </div>
                            </div>
                            {workflow.prompt && (
                                <p className="aah-text-[11px] aah-text-slate-600 aah-line-clamp-2">
                                    {workflow.prompt}
                                </p>
                            )}
                        </div>
                    ))}
                </div>
            </div>

            {workflowResults && (
                <div className="aah-space-y-2 aah-border-t aah-border-slate-200 aah-pt-2">
                    <div className="aah-font-semibold">Results</div>
                    <div className="aah-rounded-md aah-border aah-border-slate-200 aah-bg-white aah-p-2 aah-space-y-2">
                        <div>
                            <div className="aah-text-[11px] aah-font-semibold">Prompt used</div>
                            <div className="aah-text-[11px] aah-text-slate-800 aah-whitespace-pre-wrap">
                                {workflowResults.prompt || promptDraft}
                            </div>
                        </div>
                        {workflowResults.results && (
                            <div className="aah-space-y-2">
                                {Object.entries(workflowResults.results).map(([id, result]) => (
                                    <div key={id} className="aah-rounded aah-border aah-border-slate-100 aah-bg-slate-50 aah-p-2">
                                        <div className="aah-font-semibold aah-text-[12px]">{id}</div>
                                        <pre className="aah-text-[11px] aah-whitespace-pre-wrap aah-text-slate-800">
                                            {JSON.stringify(result, null, 2)}
                                        </pre>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}

function buildPromptPreview(selectedAbilityIds, abilities, postId) {
    if (!selectedAbilityIds || selectedAbilityIds.length === 0) {
        return "Select abilities to build a combined prompt.";
    }

    const lines = selectedAbilityIds
        .map((id) => abilities.find((a) => a.id === id))
        .filter(Boolean)
        .map((ability, idx) => `${idx + 1}. ${ability.label}: ${ability.description}`);

    return `Post ID: ${postId}. Apply these abilities in order and summarize outputs clearly:\n${lines.join("\n")}`;
}

document.addEventListener("DOMContentLoaded", () => {
    const rootEl = document.getElementById("aah-content-steward-root");
    if (!rootEl) return;

    const root = createRoot(rootEl);
    root.render(<MetaBoxApp />);
});
