import { useEffect } from "react"
import useStore from "../store"
import { MorphoTokensOptions, MorphoVault } from "../types"
import { MORPHO_STRATEGY_TOKENS } from "@/components/shared/constants"
import { Address } from "@/components/shared/types"
import {
  formatUnits,
  sliceDecimalString,
  formatAmountWithOptions,
} from "@/utils"
import { WETH_ADDRESS } from "@/constants"

export default function useMorphoVaults(preferredVaults?: Address[]) {
  const { fetchMorphoVaults, morphoVaults } = useStore()

  const currentVault = (token: MorphoTokensOptions) => {
    if (!token) return { apy: "--", liquidity: "--", supply: "--", name: "" }

    for (const preferredVault of preferredVaults || []) {
      const foundVault = morphoVaults.vaults.find(
        (item) => item.address.toLowerCase() === preferredVault.toLowerCase(),
      )

      if (foundVault) {
        return {
          name: foundVault.name,
          apy: `${foundVault.state.netApy.toFixed(2)} %`,
          liquidity: formatAmountWithOptions(
            formatUnits(foundVault.liquidity.underlying, 18),
          ),
          supply: `$ ${formatAmountWithOptions(
            foundVault.supply.usd.toString(),
          )}`,
        }
      }
    }

    switch (token) {
      case "weth": {
        const matchedVault = morphoVaults.vaultMapping.get(WETH_ADDRESS)

        if (matchedVault) {
          return {
            name: matchedVault.name,
            apy: `${matchedVault.state.netApy.toFixed(2)} %`,
            liquidity: formatAmountWithOptions(
              formatUnits(matchedVault.liquidity.underlying, 18),
            ),
            supply: `$ ${formatAmountWithOptions(
              matchedVault.supply.usd.toString(),
            )}`,
          }
        }
      }

      case "usdc": {
        const matchedVault = morphoVaults.vaultMapping.get(
          MORPHO_STRATEGY_TOKENS.usdc.address.toLowerCase() as Address,
        )

        if (matchedVault) {
          return {
            name: matchedVault.name,
            apy: `${matchedVault?.state.netApy.toFixed(2)} %`,
            liquidity: formatAmountWithOptions(
              formatUnits(matchedVault.liquidity.underlying, 6),
            ),
            supply: `$ ${formatAmountWithOptions(
              matchedVault.supply.usd.toString(),
            )}`,
          }
        }
      }
    }
    return { apy: "--", liquidity: "--", supply: "--", name: "" }
  }

  useEffect(() => {
    if (!morphoVaults.loading) return
    const fetchVaults = async () => {
      await fetchMorphoVaults()
    }
    fetchVaults()
  }, [morphoVaults.loading, fetchMorphoVaults])

  return { currentVault, allVaults: morphoVaults.vaults }
}
