/* eslint-disable @typescript-eslint/no-explicit-any */
import { proxy, snapshot, subscribe, useSnapshot } from 'valtio';

function proxyWithPersistant<V>(
  val: V,
  opts: {
    key: string;
  },
) {
  const local = localStorage.getItem(opts.key);
  const state = proxy(local ? JSON.parse(local) : val);
  subscribe(state, () => {
    localStorage.setItem(opts.key, JSON.stringify(snapshot(state)));
  });
  return state;
}

type StorageType = {
  access_token: string | undefined;
};

const storage: StorageType = proxyWithPersistant(
  {
    access_token: undefined,
  },
  {
    key: process.env.TOKEN_NAME as string,
  },
);

type SessionType = {
  ready: boolean;
  user?: any;
  campus?: {
    id: number;
    name: string;
  };
  permissions?: any;
  apiKeys: string[];
  loading: number;
};

const session: SessionType = proxy({
  ready: false,
  user: undefined,
  campus: undefined,
  permissions: undefined,
  apiKeys: [],
  loading: 0,
});

export const state = proxy({
  storage,
  session,
});

export function useMyState() {
  const snap = useSnapshot(state);
  return { snap };
}
