import { createContext, useContext, useCallback, useEffect, useState } from "react";
import { listWorkspaces, createWorkspace } from "../api/workspaces";

const WorkspaceContext = createContext();

const getInitialCache = () => {
    try {
        const raw = localStorage.getItem("dw_workspaces_cache");
        return raw ? JSON.parse(raw) : [];
    } catch {
        return [];
    }
};

export function WorkspaceProvider({ children }) {
    const [workspaces, setWorkspaces] = useState(getInitialCache);
    const [currentId, setCurrentId] = useState(() => localStorage.getItem("dw_workspace_id") || null);
    const [loading, setLoading] = useState(() => {
        const cached = getInitialCache();
        const savedId = localStorage.getItem("dw_workspace_id");
        return !(cached.length > 0 && (savedId ? cached.some((w) => w.id === savedId) : true));
    });
    const [error, setError] = useState(null);

    const refresh = useCallback(async () => {
        setError(null);
        try {
            const list = await listWorkspaces();

            if (!Array.isArray(list)) {
                if (list?.detail) setError(list.detail);
                return;
            }

            if (list.length === 0) {
                const created = await createWorkspace({
                    name: "Default Workspace",
                    description: "Created automatically for document uploads.",
                });
                if (created?.detail) {
                    setError(created.detail);
                    return;
                }
                setWorkspaces([created]);
                setCurrentId(created.id);
                localStorage.setItem("dw_workspace_id", created.id);
                localStorage.setItem("dw_workspaces_cache", JSON.stringify([created]));
                return;
            }

            setWorkspaces(list);
            localStorage.setItem("dw_workspaces_cache", JSON.stringify(list));
            setCurrentId((prev) => {
                const saved = prev || localStorage.getItem("dw_workspace_id");
                if (saved && list.some((w) => w.id === saved)) return saved;
                localStorage.setItem("dw_workspace_id", list[0].id);
                return list[0].id;
            });
        } catch (err) {
            setError("Couldn't load workspaces.");
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        refresh();
    }, [refresh]);

    const selectWorkspace = useCallback((id) => {
        setCurrentId(id);
        localStorage.setItem("dw_workspace_id", id);
    }, []);

    const addWorkspace = useCallback(async (name, description = "") => {
        const created = await createWorkspace({ name, description });
        if (created?.detail) {
            setError(created.detail);
            return null;
        }
        setWorkspaces((prev) => {
            const next = [...prev, created];
            localStorage.setItem("dw_workspaces_cache", JSON.stringify(next));
            return next;
        });
        setCurrentId(created.id);
        localStorage.setItem("dw_workspace_id", created.id);
        return created;
    }, []);

    const currentWorkspace = workspaces.find((w) => w.id === currentId) || (workspaces.length > 0 ? workspaces[0] : null);

    const value = {
        workspace: currentWorkspace,
        workspaces,
        loading,
        error,
        selectWorkspace,
        addWorkspace,
        refresh,
    };

    return <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>;
}

export const useWorkspaceContext = () => useContext(WorkspaceContext);
