"use client";

import { useCallback, useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { experienceApi } from "@/modules/experience/services/experience-api";

const STORAGE_KEY = "experience.selectedWorkspaceId";

export function useExperienceWorkspace() {
  const { tenantId } = useTenantId();
  const [workspaceId, setWorkspaceIdState] = useState<string | null>(null);

  const workspacesQ = useQuery({
    queryKey: ["experience", tenantId, "workspaces"],
    queryFn: () => experienceApi.workspaces.list(tenantId!),
    enabled: !!tenantId,
    staleTime: 60_000,
  });

  useEffect(() => {
    if (typeof window === "undefined") return;
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) setWorkspaceIdState(stored);
  }, []);

  useEffect(() => {
    if (!workspacesQ.data?.length) return;
    const stored = typeof window !== "undefined" ? localStorage.getItem(STORAGE_KEY) : null;
    const valid = stored && workspacesQ.data.some((w) => String(w.id) === stored);
    if (!valid && workspacesQ.data[0]?.id) {
      const id = String(workspacesQ.data[0].id);
      setWorkspaceIdState(id);
      localStorage.setItem(STORAGE_KEY, id);
    }
  }, [workspacesQ.data]);

  const setWorkspaceId = useCallback((id: string) => {
    setWorkspaceIdState(id);
    localStorage.setItem(STORAGE_KEY, id);
  }, []);

  const workspace = workspacesQ.data?.find((w) => String(w.id) === workspaceId) ?? null;

  return {
    workspaceId,
    workspace,
    workspaces: workspacesQ.data ?? [],
    setWorkspaceId,
    isLoading: workspacesQ.isLoading,
    refetch: workspacesQ.refetch,
  };
}
