import { MorphoTokensOptions } from "@/components/morphoStrategy/types"
import { Address } from "../types"

const storagePrefix = "psp"

const storageKeys = {
  deployedMorphoStrategyConsole: "deployedMorphoStrategyConsole",
  aiChatChoices: "aiChatChoices",
  deployedSwapAgentConsole: "deployedSwapAgentConsole",
}

type AiChatChoice = { rebalanceFrequency: string; preferredVaults: Address[] }

const localStorageService = {
  setDeployedMorphoStrategyConsole: (
    consoleAddress: Address,
    token: MorphoTokensOptions,
    eoa: Address,
  ) => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.deployedMorphoStrategyConsole}_${eoa}`
      const historyData =
        JSON.parse(window.localStorage.getItem(storageKey) as string) || {}

      const updatedDate = { ...historyData, [token]: consoleAddress }
      window.localStorage.setItem(storageKey, JSON.stringify(updatedDate))
    }
  },
  getDeployedSwapAgentConsole: (): string | undefined => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.deployedMorphoStrategyConsole}`
      return window.localStorage.getItem(storageKey) as string
    }
  },
  setDeployedSwapAgentConsole: (consoleAddress: Address) => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.deployedMorphoStrategyConsole}`
      window.localStorage.setItem(storageKey, consoleAddress)
    }
  },
  clearDeployedSwapAgentConsole: () => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.deployedMorphoStrategyConsole}`
      window.localStorage.removeItem(storageKey)
    }
  },
  getDeployedMorphoStrategyConsole: (
    eoa: Address,
    token: MorphoTokensOptions,
  ): string | undefined => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.deployedMorphoStrategyConsole}_${eoa}`

      const cache = window.localStorage.getItem(storageKey) as string

      const parsedCache = JSON.parse(cache) || {}
      return parsedCache[token]
    }
  },

  setAiChatChoices: (
    eoa: Address,
    token: MorphoTokensOptions,
    choices: AiChatChoice,
  ) => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.aiChatChoices}_${eoa}_${token}`
      window.localStorage.setItem(storageKey, JSON.stringify(choices))
    }
  },

  getAiChatChoices: (
    eoa: Address,
    token: MorphoTokensOptions,
  ): AiChatChoice | null => {
    if (typeof window !== "undefined") {
      const storageKey = `${storagePrefix}_${storageKeys.aiChatChoices}_${eoa}_${token}`
      const cache = window.localStorage.getItem(storageKey) as string
      const parsedCache = JSON.parse(cache) as AiChatChoice
      return parsedCache || null
    }
    return null
  },
}

export default localStorageService
