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';
const HIDE_SOUPS_KEY = 'hide_soups';

export type SettingsContextProps = {
  bankAccount?: string,
  holderName?: string,
  hideSoups?: boolean,
  setBankAccountNumber: (accountNumber?: string) => void,
  setBankAccountHolderName: (holderName?: string) => void,
  setHideSoupsOption: (hideSoups?: boolean) => void,
}

type ContextProps = {
  children: ReactNode
}

const settingsContext = React.createContext<SettingsContextProps | null>(null);

export function ProvideSettings(props: ContextProps) {
  const settings = useProvideSettings();
  return <settingsContext.Provider value={settings}>{props.children}</settingsContext.Provider>
}

export const useSettings = () => {
  return useContext(settingsContext);
}

function useProvideSettings(): SettingsContextProps {
  const [bankAccount, setBankAccount] = useState<string | undefined>();
  const [holderName, setHolderName] = useState<string | undefined>();
  const [hideSoups, setHideSoups] = useState<boolean | 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);
    }
    const hideSoups = localStorage.getItem(HIDE_SOUPS_KEY);
    if (hideSoups !== null) {
      setHideSoups(hideSoups === 'true' ? true : false);
    }
  }, [])

  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]);

  useEffect(() => {
    if (hideSoups) {
      localStorage.setItem(HIDE_SOUPS_KEY, hideSoups ? 'true' : 'false');
    } else {
      localStorage.removeItem(HIDE_SOUPS_KEY);
    }
  }, [hideSoups]);

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

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

  function setHideSoupsOption(hideSoups?: boolean) {
    setHideSoups(hideSoups);
  }

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