import React, {useCallback, useEffect, useState} from 'react';
import Context from './context';
import useUnicornFinance from '../../hooks/useUnicornFinance';
import {Bank} from '../../unicorn-finance';
import config, {bankDefinitions} from '../../config';

const Banks: React.FC = ({children}) => {
  const [banks, setBanks] = useState<Bank[]>([]);
  const unicornFinance = useUnicornFinance();
  const isUnlocked = unicornFinance?.isUnlocked;

  const fetchPools = useCallback(async () => {
    const banks: Bank[] = [];

    for (const bankInfo of Object.values(bankDefinitions)) {
      if (bankInfo.finished) {
        if (!unicornFinance.isUnlocked) continue;

        // only show pools staked by user
        const balance = await unicornFinance.stakedBalanceOnBank(
          bankInfo.contract,
          bankInfo.poolId,
          unicornFinance.myAccount,
        );
        if (balance.lte(0)) {
          continue;
        }
      }
      banks.push({
        ...bankInfo,
        address: config.deployments[bankInfo.contract].address,
        depositToken: unicornFinance.externalTokens[bankInfo.depositTokenName],
        earnToken: bankInfo.earnTokenName === 'UNICORN' ? unicornFinance.UNICORN : unicornFinance.WINGS,
      });
    }
    banks.sort((a, b) => (a.sort > b.sort ? 1 : -1));
    setBanks(banks);
  }, [unicornFinance, setBanks]);

  useEffect(() => {
    if (unicornFinance) {
      fetchPools().catch((err) => console.error(`Failed to fetch pools: ${err.stack}`));
    }
  }, [isUnlocked, unicornFinance, fetchPools]);

  return <Context.Provider value={{banks}}>{children}</Context.Provider>;
};

export default Banks;
