/* 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;
  };
  company?: {
    id?: number;
    name?: string;
  };
  company_configs?: {
    config_value?: {
      logo?: {
        url?: string;
      }[];
      admin_logo?: {
        url?: string;
      }[];
    };
  };
  permissions?: any;
  apiKeys: string[];
  loading: number;
  current_project?: {
    id: number;
    name: string;
  };
};

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

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

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