import React, { ReactNode, useContext, useState } from "react"
import { useEffect } from "react"

const BANK_ACCOUNT_NUMBER_KEY = 'bank_account_number';
const BANK_ACCOUNT_HOLDER_KEY = 'bank_account_holder_name';

export type BankContextProps = {
  bankAccount?: string,
  holderName?: string,
  setBankAccountNumber: (accountNumber?: string) => void,
  setBankAccountHolderName: (holderName?: string) => void,
}

type ContextProps = {
  children: ReactNode
}

const bankContext = React.createContext<BankContextProps | null>(null);

export function ProvideBank(props: ContextProps) {
  const bank = useProvideBank();
  return <bankContext.Provider value={bank}>{props.children}</bankContext.Provider>
}

export const useBank = () => {
  return useContext(bankContext);
}

function useProvideBank(): BankContextProps {
  const [bankAccount, setBankAccount] = useState<string | undefined>();
  const [holderName, setHolderName] = useState<string | undefined>();

  useEffect(() => {
    const accountNumber = localStorage.getItem(BANK_ACCOUNT_NUMBER_KEY);
    if (accountNumber) {
      setBankAccount(accountNumber);
    }
    const holderName = localStorage.getItem(BANK_ACCOUNT_HOLDER_KEY);
    if (holderName) {
      setHolderName(holderName);
    }
  }, [])

  useEffect(() => {
    if (bankAccount) {
      localStorage.setItem(BANK_ACCOUNT_NUMBER_KEY, bankAccount)
    } else {
      localStorage.removeItem(BANK_ACCOUNT_NUMBER_KEY);
    }
  }, [bankAccount]);

  useEffect(() => {
    if (holderName) {
      localStorage.setItem(BANK_ACCOUNT_HOLDER_KEY, holderName);
    } else {
      localStorage.removeItem(BANK_ACCOUNT_HOLDER_KEY);
    }
  }, [holderName]);

  function setBankAccountNumber(bankAccount?: string) {
    setBankAccount(bankAccount);
  }

  function setBankAccountHolderName(holderName?: string) {
    setHolderName(holderName);
  }

  return {
    bankAccount,
    holderName,
    setBankAccountNumber,
    setBankAccountHolderName,
  }
}
