import { useLocation, useNavigate } from 'react-router';
import { useGlobal } from 'hooks/useGlobal';
import { useUserState } from 'state/useUserState';
import { generateSlug } from 'helpers/slug';
import {
  CREATING_DASHBOARD_KEY,
  EDITING_DASHBOARD_KEY,
  NEW_DASH_NAME_KEY,
  NEW_DASH_DESC_KEY,
  NEW_DASH_TEMPLATE_KEY,
} from './constants';

type NewDashboardSeed = {
  /** Pre-fills the name field. Falls back to a generated slug, which is what the plain button does. */
  name?: string;
  /** Home-relative folder the dashboard should be rooted at, leading slash, e.g. `/Pictures/Photos`. */
  path?: string;
};

/**
 * Opens the create-dashboard form, optionally seeded. Returns the opener, not state.
 *
 * The seed is spread across four `useGlobal` form-draft keys plus `files/currentPath` — `NewDashboardForm`
 * derives its `cwd` from that last one rather than holding a folder field of its own — so "start creating a
 * dashboard" is five writes in a specific order, not one. It lived inline in the New Dashboard button, and
 * the file browser's "Create Dashboard here" tried to express the same intent as a URL instead
 * (`/dashboards/new?name=…&cwd=…`). That URL never had a route: `new` matched `/dashboards/:id`, found no
 * dashboard by that id, and redirected to the bare list, dropping the params — so the menu item had been
 * doing nothing since the workspaces→dashboards rename in `927267e`. One opener, two call sites, no URL
 * contract to keep in sync.
 *
 * Seeding a draft *and then* navigating is why the callers stay buttons rather than becoming links: a link
 * cannot express the "and then".
 */
export const useNewDashboardDraft = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [, setCreating] = useGlobal<boolean>(CREATING_DASHBOARD_KEY, false);
  const [, setEditing] = useGlobal<string | null>(EDITING_DASHBOARD_KEY, null);
  const [, setName] = useGlobal<string>(NEW_DASH_NAME_KEY, '');
  const [, setDescription] = useGlobal<string>(NEW_DASH_DESC_KEY, '');
  const [, setTemplateIdx] = useGlobal<number>(NEW_DASH_TEMPLATE_KEY, 0);
  const [, setFilePath] = useUserState<string>('files/currentPath', '/');

  return ({ name, path }: NewDashboardSeed = {}) => {
    setEditing(null);
    setName(name?.trim() || generateSlug());
    setDescription('');
    setTemplateIdx(0);
    setFilePath(path || '/');
    setCreating(true);
    // `/dashboards` with no query — which is also how `?selected=` gets cleared, since an open form and a
    // selected dashboard are different states. Replace when already there so opening the form is not a
    // history entry you have to press Back through twice.
    navigate('/dashboards', { replace: location.pathname === '/dashboards' });
  };
};
