/* eslint-disable react/destructuring-assignment */
/* eslint-disable @typescript-eslint/no-unused-vars */
// eslint-disable-next-line object-curly-newline
import axios from 'axios';
import type { ReactNode } from 'react';
import type React from 'react';
import {
	createContext,
	useContext,
	useDeferredValue,
	useEffect,
	useReducer,
	useState
} from 'react';

import environment from '../../Environments/environment';
import companyDropdownPredefinedValues from '../../Pages/Companies/Companies.helper';
import type { CompanyDbModel } from '../../Pages/Companies/Components/CompaniesComponents.helper';
import type {
	Action,
	FinancialsModel
} from '../../Pages/Financials/Components/FinancialsForm/FinancialsForm.helper';
import { formDefaultValues } from '../../Pages/Financials/Components/FinancialsForm/FinancialsForm.helper';
import styles from '../../Pages/Financials/Financials.module.scss';
import type {
	MoneyMultiplierContextInterface,
	MoneyMultiplierForCeosContextModel
} from '../../Pages/MoneyForCeos/moneyMultiplierForCeos.helper';
import {
	latestFinancialsHelper,
	moneyMultiplierContextDefaultValues,
	MoneyMultiplierForCeosMainContextDefault,
	reducerHandlerHelper
} from '../../Pages/MoneyForCeos/moneyMultiplierForCeos.helper';
import type { GlobalStateModel } from '../global/GlobalState-context';
import { GlobalStateContext } from '../global/GlobalState-context';
import { Users } from './financials-form-context-helper';
import netCashFlowHandler, {
	ebitdaMapValues,
	helperMonths,
	priceIncreaseCashFlowHandler
} from './financialsContext.helper';
import type { IndustryModel, NetFlowHandlerInterface } from './financialsContext.helper';
import { useSelector } from 'react-redux';
import type { RootState } from '../../ReduxState/store';
import getCompanyType from '../../utils/getCompanyType';

const { apiUrl, backendRoutes } = environment;

export type FinancialsContextModel = MoneyMultiplierForCeosContextModel;

export const FinancialsContext: React.Context<FinancialsContextModel> =
	createContext<FinancialsContextModel>(MoneyMultiplierForCeosMainContextDefault);

const FinancialsContextProvider: React.FC<{ children: ReactNode }> = (props: {
	children: ReactNode;
}) => {
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const companyType = getCompanyType(selectedCompany);
	const [financialForEdit, setFinancialForEdit] = useState<FinancialsModel | undefined>({
		company_id: '',
		selected: false,
		financials_id: '',
		cognito_username: '',
		input: formDefaultValues
	});

	const initialStateMMC: MoneyMultiplierContextInterface = moneyMultiplierContextDefaultValues;
	const [selectedItems, setSelectedItems] = useState<string[]>([]);
	const [selectedCompanyFinancials, setSelectedCompanyFinancials] = useState<FinancialsModel[]>([
		{
			financials_id: '',
			input: formDefaultValues,
			company_id: '',
			selected: true,
			cognito_username: ''
		}
	]);
	const [plan, setPlan] = useState<string>('Basic Plan');
	const [classForPopup, setClassForPopup] = useState<string>('');
	const [whatIsChecked, setWhatIsChecked] = useState<number>(0);
	const [selectedFinancials, setSelectedFinancials] = useState<FinancialsModel[]>([
		{
			financials_id: '',
			input: formDefaultValues,
			company_id: '',
			selected: true,
			cognito_username: ''
		}
	]);

	function reducerHandler(
		state: MoneyMultiplierContextInterface,
		action: Action
	): MoneyMultiplierContextInterface {
		return reducerHandlerHelper(state, action, initialStateMMC);
	}

	const [moneyMultiplierForCeosInputs, dispatchMoneyMultiplierForCeosInputs] = useReducer(
		reducerHandler,
		initialStateMMC
	);
	const [activateUser, setActivateUser] = useState<number>(0);
	const firstFinancial: FinancialsModel = JSON.parse(
		localStorage.getItem('first-financial') as string
	);
	const secondFinancial: FinancialsModel = JSON.parse(
		localStorage.getItem('second-financial') as string
	);
	const thirdFinancial: FinancialsModel = JSON.parse(
		localStorage.getItem('third-financial') as string
	);
	// const firstFinancial: FinancialsModel = JSON.parse(
	// 	localStorage.getItem('first-financial') as string
	// );
	// const secondFinancial: FinancialsModel = JSON.parse(
	// 	localStorage.getItem('second-financial') as string
	// );
	// const thirdFinancial: FinancialsModel = JSON.parse(
	// 	localStorage.getItem('third-financial') as string
	// );
	const [isDemoActive, setIsDemoActive] = useState<boolean>(false);
	const [companies, setCompanies] = useState<CompanyDbModel[]>([]);
	const [selectedIndustryForEbitda, setSelectedIndustryForEbitda] = useState<IndustryModel>({
		id: 0,
		sixToTen: 0,
		twoToFive: 0,
		name: '',
		zeroToOne: 0
	});
	const [priceIncreaseIndex, setPriceIncreaseIndex] = useState<number>(
		JSON.parse(localStorage.getItem('priceIncreaseIndex') as string)
	);
	const [volumeIncreaseIndex, setVolumeIncreaseIndex] = useState<number>(
		JSON.parse(localStorage.getItem('volumeIncreaseIndex') as string)
	);
	const [cogsIndex, setCogsIndex] = useState<number>(
		JSON.parse(localStorage.getItem('cogsIndex') as string)
	);
	const [overheadReductionIndex, setOverheadReductionIndex] = useState<number>(
		JSON.parse(localStorage.getItem('overheadReductionIndex') as string)
	);
	const [debtorsDayReductionIndex, setDebtorsDayReductionIndex] = useState<number>(
		JSON.parse(localStorage.getItem('debtorsDayReduction') as string)
	);
	const [reductionWipDaysIndex, setReductionWipDaysIndex] = useState<number>(
		JSON.parse(localStorage.getItem('reductionWipDays') as string)
	);
	const [increaseInCreditorsDaysIndex, setIncreaseInCreditorsDaysIndex] = useState<number>(
		JSON.parse(localStorage.getItem('increaseInCreditorsDays') as string)
	);
	const [popupClass, setPopupClass] = useState<string>('');
	const globalContext: GlobalStateModel = useContext(GlobalStateContext);

	function activateUserHandler(planName: string): void {
		if (typeof globalContext.financials !== 'string') {
			const selectedFinancialsId = globalContext.financials.map((item) => item.financials_id);
			if (globalContext.loggedInUser?.plan.title === 'Basic Plan') {
				setSelectedItems(selectedFinancialsId);
				setActivateUser(Users.basic);
			} else if (globalContext.loggedInUser?.plan.title === 'Grow Plan') {
				setSelectedItems(selectedFinancialsId);
				setActivateUser(Users.grow);
			}
		}
	}

	function getAllStates(
		priceIncrease: number,
		volumeIncrease: number,
		cogs: number,
		overheadReduction: number,
		debtorsDayReduction: number,
		reductionWipDays: number,
		increaseInCreditorsDays: number,
		increaseInDeferredRevenueDays: number
	): void {
		console.log('>>> GETTING ALL STATES');
		let lastFinancial: FinancialsModel;
		if (thirdFinancial) {
			lastFinancial = thirdFinancial;
		} else {
			lastFinancial = secondFinancial;
		}
		const {
			lastYearCogs,
			revenue,
			COGS: cogsFromLastFinancialPeriod,
			grossProfit,
			tradeDebtors,
			stock,
			tradeCreditors,
			deferredRevenue,
			grossMargin,
			ebit,
			month,
			year
		} = latestFinancialsHelper(lastFinancial);
		const cogsReductionEbit: number = Math.round((lastYearCogs * +cogs) / 100);
		// const firstResultCogs: number = (stock / revenue) * 365;
		const firstResultCogs: number = (stock / lastYearCogs) * 365;
		const secondResultCogs: number = (tradeCreditors / lastYearCogs) * 365;
		// cogs reduction calculation
		console.log('first term for cogs', stock, revenue, (stock / revenue) * 365);
		console.log('first term for cogs', firstResultCogs, 'second term for cogs', secondResultCogs);
		const cogsReductionCashFlow: number =
			((+firstResultCogs - +secondResultCogs) / 365) * +cogsReductionEbit + +cogsReductionEbit;
		console.log('THIS IS COGS FROM LAST FINANCIAL PERIOD', cogsFromLastFinancialPeriod);
		const workingCapital =
			((tradeDebtors + stock - tradeCreditors - deferredRevenue) / revenue) * 100;
		const grossMarginWorkingCapitalPercent = +grossMargin.toFixed(2) - +workingCapital.toFixed(2);
		const overhead: number = (revenue / 365) * +overheadReduction;
		localStorage.setItem('priceIncreaseIndex', JSON.stringify(priceIncrease));
		localStorage.setItem('volumeIncreaseIndex', JSON.stringify(volumeIncrease));
		localStorage.setItem('cogsIndex', JSON.stringify(cogs));
		localStorage.setItem('overheadReductionIndex', JSON.stringify(overheadReduction));
		localStorage.setItem('debtorsDayReduction', JSON.stringify(debtorsDayReduction));
		localStorage.setItem('reductionWipDays', JSON.stringify(reductionWipDays));
		localStorage.setItem('increaseInCreditorsDays', JSON.stringify(increaseInCreditorsDays));
		localStorage.setItem(
			'increaseInDeferredRevenueDays',
			JSON.stringify(increaseInDeferredRevenueDays)
		);
		setPriceIncreaseIndex(priceIncrease);
		setVolumeIncreaseIndex(volumeIncrease);
		setCogsIndex(cogs);
		setOverheadReductionIndex(overheadReduction);
		setDebtorsDayReductionIndex(debtorsDayReduction);
		setReductionWipDaysIndex(reductionWipDays);
		setIncreaseInCreditorsDaysIndex(increaseInCreditorsDays);

		dispatchMoneyMultiplierForCeosInputs({
			type: 'PRICE_INCREASE_PERCENT_EBIT',
			value: +priceIncrease
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'PRICE_INCREASE_NET_CASH_FLOW',
			value: priceIncreaseCashFlowHandler({
				priceIncreaseEbit: Math.round((+revenue * +priceIncrease) / 100),
				lastFinancialTradeDebtors: +tradeDebtors,
				lastFinancialRevenue: +revenue
			})
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'PRICE_INCREASE_EBIT',
			value: Math.round((+revenue * +priceIncrease) / 100)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'VOLUME_INCREASE_EBIT',
			value: Math.round((+grossProfit * +volumeIncrease) / 100)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'VOLUME_INCREASE_NET_CASH_FLOW',
			value: Math.round(
				(revenue * (+grossMarginWorkingCapitalPercent.toFixed(2) / 100) * +volumeIncrease) / 100
			)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'VOLUME_INCREASE_PERCENT_INPUT',
			value: +volumeIncrease
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'COGS_PERCENT_INPUT',
			value: +cogs
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'COGS_EBIT',
			value: Math.round(cogsReductionEbit)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'COGS_CASH_FLOW',
			value: Math.round(cogsReductionCashFlow)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'OVERHEAD_PERCENT_INPUT',
			value: +overheadReduction
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'OVERHEAD_EBIT',
			value: Math.round(((grossProfit - ebit) * +overheadReduction) / 100)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'OVERHEAD_CASH_FLOW',
			value: Math.round(((grossProfit - ebit) * +overheadReduction) / 100)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'DEBTORS_DAY_CASH_FLOW',
			value: Math.round((revenue / 365) * debtorsDayReduction)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'DEBTORS_DAY_PERCENT_INPUT',
			value: +debtorsDayReduction
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'REDUCTION_IN_WIP',
			// value: Math.round((revenue / 365) * +reductionWipDays)
			value:
				companyType === 'All Other'
					? Math.round((+cogsFromLastFinancialPeriod / 365) * +reductionWipDays)
					: Math.round((+revenue / 365) * +reductionWipDays)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'REDUCTION_IN_WIP_DAYS_INPUT',
			value: +reductionWipDays
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'INCREASE_CREDITORS_DAYS',
			value: Math.round((lastYearCogs / 365) * +increaseInCreditorsDays)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'INCREASE_DEFERRED_REVENUE_DAYS',
			value: Math.round((+deferredRevenue / 365) * +increaseInDeferredRevenueDays)
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'FIRST_MONTH',
			value: month
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'FIRST_YEAR',
			value: year
		});
	}

	useEffect(() => {
		const selectedPlan: string = localStorage.getItem('plan') as string;
		activateUserHandler(selectedPlan);
		getAllStates(1, 1, 1, 1, 1, 1, 1, 1);
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	function editFinancialsHandler(event: FinancialsModel | undefined): void {
		setFinancialForEdit(event);
	}

	const [selectedFinancialsId, setSelectedFinancialsId] = useState<string[]>([]);

	const preloadedFinancials = useDeferredValue(
		JSON.parse(localStorage.getItem('pre-loaded-financials') as string)
	);

	function compare(a: { year: number; month: string }, b: { year: number; month: string }) {
		if (a.year < b.year) {
			return -1;
		}
		if (a.year > b.year) {
			return 1;
		}
		return 0;
	}

	const {
		weightedAverageEBITDA,
		ebit,
		netCashFlow,
		priceIncreaseEbit,
		priceIncreaseNetCashFlow,
		volumeIncrease,
		volumeIncreaseEbit,
		volumeIncreaseCashFlow,
		cogsEbit,
		cogsCashFlow,
		overheadEbit,
		overheadCashFlow,
		debtorsDayCashFlow,
		reductionInWip,
		increaseCreditorsDays,
		netCashFlowSum,
		ebitSum,
		netCashFlowEnd,
		ebitEnd,
		endingMonth,
		endingYear,
		equityValuation,
		actualEquity,
		lessTotalDebt,
		ebitdaValue,
		priceIncreaseImpact,
		volumeIncreaseImpact,
		cogsImpact,
		cashImpact,
		totalImpact,
		enhancedBusinessValueIndicator,
		impactOnMultiplierAdjustmentOnValuation,
		firstMonth,
		lastMonth,
		firstYear,
		lastYear,
		increaseDeferredRevenueDays,
		profitImpactOnValuation,
		overheadReduction
	} = moneyMultiplierForCeosInputs;

	function getInOrderFinancials(selectedFinancialsItems: FinancialsModel[]): void {
		const objectItem: { year: number; month: string }[] = [];
		selectedFinancialsItems.filter(({ input }) =>
			helperMonths.find((month) => {
				if (input['Month Ending'] === month.month) {
					objectItem.push({
						year: +input['Year Ending'],
						month: month.index.toString()
					});
				}
				return input['Month Ending'] === month.month;
			})
		);
		const ordered = objectItem.sort(compare);
		const getOrdered: { year: number; month: string }[] = [];
		ordered.map((item) =>
			helperMonths.filter((month) => {
				if (month.index === +item.month) {
					getOrdered.push({
						year: item.year,
						month: month.month
					});
				}
				return month.index === +item.month;
			})
		);
		selectedFinancialsItems.filter((financialItem) => {
			if (
				+financialItem.input['Year Ending'] === getOrdered[0]?.year &&
				financialItem.input['Month Ending'] === getOrdered[0]?.month
			) {
				localStorage.setItem('first-financial', JSON.stringify(financialItem));
			} else if (
				+financialItem.input['Year Ending'] === getOrdered[1]?.year &&
				financialItem.input['Month Ending'] === getOrdered[1]?.month
			) {
				localStorage.setItem('second-financial', JSON.stringify(financialItem));
			} else if (
				+financialItem.input['Year Ending'] === getOrdered[2]?.year &&
				financialItem.input['Month Ending'] === getOrdered[2]?.month
			) {
				localStorage.setItem('third-financial', JSON.stringify(financialItem));
			}
			return financialItem;
		});
	}

	function findSelectedFinancials(selectedId: string[]): void {
		const allFinancials: FinancialsModel[] | string = globalContext.financials;
		let selected: FinancialsModel[] = [];
		let allFinancialsFromSelectedCompany: FinancialsModel[] = [];
		// TOREVIEW:
		// make sure the selectedId is array, it can be a string
		if (Array.isArray(selectedId) && selectedId.length !== 0) {
			if (preloadedFinancials) {
				if (preloadedFinancials.length !== 0 && typeof preloadedFinancials !== 'string') {
					allFinancialsFromSelectedCompany = preloadedFinancials;
				}
			} else {
				allFinancialsFromSelectedCompany = selectedCompanyFinancials;
			}
			selected = allFinancialsFromSelectedCompany.filter((financial) =>
				selectedId.find((id) => financial.financials_id === id)
			);

			console.log('selected', selected, 'all financials', allFinancials);
			if (selected.length === 0) {
				if (typeof allFinancials !== 'string' && Array.isArray(allFinancials)) {
					selected = allFinancials.filter((financial: FinancialsModel) =>
						selectedId.find((id) => financial.financials_id === id)
					);
				}
			}
		}
		setSelectedFinancialsId(selectedId);
		setSelectedFinancials(selected);
		localStorage.setItem('selected-financials', JSON.stringify(selected));
		getInOrderFinancials(selected);
		console.log('REMOVING ITEMS FROM LS from FC');
		if (selected.length === 0) {
			localStorage.removeItem('first-financial');
			localStorage.removeItem('second-financial');
			localStorage.removeItem('third-financial');
		} else if (selected.length === 1) {
			localStorage.removeItem('second-financial');
			localStorage.removeItem('third-financial');
		} else if (selected.length === 2) {
			localStorage.removeItem('third-financial');
		}
	}

	function selectedItemsHandler(event: string): void {
		console.log('selected items', event);
		dispatchMoneyMultiplierForCeosInputs({
			type: 'SELECTED_FINANCIALS',
			value: event
		});
		setSelectedItems((prevState) => {
			findSelectedFinancials([...prevState, event]);
			return [...prevState, event];
		});
	}

	function loadedSelectedItemsHandler(event: string[]): void {
		setSelectedItems(() => {
			findSelectedFinancials(event);
			return event;
		});
	}

	function unselectedItemHandler(event: string): void {
		setSelectedItems((prevState) => {
			const deselected = prevState.filter((item) => item !== event);
			findSelectedFinancials(deselected);
			return deselected;
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'UNSELECTED_FINANCIALS',
			value: event
		});
	}
	//
	useEffect(() => {
		setSelectedItems(globalContext.selectedItems);
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [globalContext.checkedFinancials]);

	function isCheckedCardHandler(id: string | undefined): void {
		if (id === 'moneyMultiplier') {
			setWhatIsChecked(0);
		} else if (id === 'moneyForGrowth') {
			setWhatIsChecked(1);
		} else if (id === 'cashFlowAnalysis') {
			setWhatIsChecked(2);
		}
	}

	useEffect(() => {
		const route: string = window.location.href.split('/')[3];

		if (route === 'cash-flow-picture') {
			setWhatIsChecked(2);
		} else if (route === 'money-for-growth') {
			setWhatIsChecked(1);
		} else if (route === 'money-for-ceos') {
			setWhatIsChecked(0);
		}
	}, []);

	useEffect(() => {
		if (selectedItems.length === 1) {
			localStorage.removeItem('second-financial');
			localStorage.removeItem('third-financial');
		}

		if (whatIsChecked === 0 && selectedItems?.length === 2) {
			localStorage.removeItem('third-financial');
			setClassForPopup(styles.collapseContainerGreen);
		} else if (whatIsChecked === 0 && selectedItems?.length !== 2) {
			setClassForPopup(styles.collapseContainer);
		} else if (whatIsChecked === 1 && selectedItems?.length === 1) {
			setClassForPopup(styles.collapseContainerGreen);
		} else if (whatIsChecked === 1 && selectedItems?.length !== 1) {
			setClassForPopup(styles.collapseContainer);
		} else if (whatIsChecked === 2 && selectedItems?.length !== 3) {
			setClassForPopup(styles.collapseContainer);
		} else if (whatIsChecked === 2 && selectedItems?.length === 3) {
			setClassForPopup(styles.collapseContainerGreen);
		}
	}, [selectedItems, setSelectedItems, whatIsChecked]);

	function financialsPrepHandler(): void {
		let lastFinancial: FinancialsModel = {
			financials_id: '',
			cognito_username: '',
			selected: false,
			company_id: '',
			input: formDefaultValues
		};
		let beforeLastFinancial: FinancialsModel = {
			financials_id: '',
			cognito_username: '',
			selected: false,
			company_id: '',
			input: formDefaultValues
		};
		if (thirdFinancial) {
			lastFinancial = thirdFinancial;
			beforeLastFinancial = secondFinancial;
		} else if (secondFinancial && !thirdFinancial) {
			lastFinancial = secondFinancial;
			beforeLastFinancial = firstFinancial;
		}

		if (!lastFinancial) {
			return;
		}
		if (
			lastFinancial &&
			beforeLastFinancial &&
			lastFinancial.input !== undefined &&
			beforeLastFinancial.input !== undefined
		) {
			const interfaceItems: NetFlowHandlerInterface = {
				cashAtBank: +beforeLastFinancial.input['Cash at Bank'],
				bankLoanCurrent: +beforeLastFinancial.input['Additional Bank Loans - Current'],
				bankLoanNonCurrent: +beforeLastFinancial.input['Additional Bank Loans - Non Current'],
				cashAtBank2: +lastFinancial.input['Cash at Bank'],
				bankLoanCurrent2: +lastFinancial.input['Additional Bank Loans - Current'],
				bankLoanNonCurrent2: +lastFinancial.input['Additional Bank Loans - Non Current']
			};
			dispatchMoneyMultiplierForCeosInputs({
				type: 'NET_CASH_FLOW',
				value: netCashFlowHandler(interfaceItems)
			});
		}
		if (lastFinancial.input !== undefined && lastFinancial?.input.COGS !== '') {
			dispatchMoneyMultiplierForCeosInputs({
				type: 'PRICE_INCREASE_EBIT',
				value: Math.round(
					// eslint-disable-next-line no-unsafe-optional-chaining
					(+lastFinancial?.input.Revenue * moneyMultiplierForCeosInputs.priceIncreasePercentEbit) /
						100
				)
			});
		}
	}

	// Money Multiplier for Ceos
	function storageFinancialsHandler(): void {
		console.log('FC: storageFinancialsHandler', selectedItems);
		localStorage.setItem('selectedItems', JSON.stringify(selectedItems));
	}

	function setEbitdaHandler(event: number): void {
		dispatchMoneyMultiplierForCeosInputs({
			type: 'EBITDA_VALUE',
			value: event.toFixed(2)
		});
	}

	useEffect(() => {
		// window.scrollTo(0, 0);
	}, []);

	useEffect(() => {
		financialsPrepHandler();
		console.log('FC: SELECTING FINANCIALS ORDER: ', selectedItems);
		let lastFinancial: FinancialsModel = {
			financials_id: '',
			cognito_username: '',
			selected: false,
			company_id: '',
			input: formDefaultValues
		};
		let beforeLastFinancial: FinancialsModel = {
			financials_id: '',
			cognito_username: '',
			selected: false,
			company_id: '',
			input: formDefaultValues
		};
		if (thirdFinancial) {
			lastFinancial = thirdFinancial;
			beforeLastFinancial = secondFinancial;
		} else if (secondFinancial) {
			lastFinancial = secondFinancial;
			beforeLastFinancial = firstFinancial;
		}
		const {
			ebit,
			month,
			year,
			deprecation,
			bankLoanCurrent,
			bankLoanNonCurrent,
			totalCurrentAssets,
			fixedAssets,
			totalLiabilities,
			tradeDebtors,
			revenue,
			tradeCreditors,
			grossProfit,
			lastYearCogs,
			totalAssets
		} = latestFinancialsHelper(lastFinancial);
		const y2GrossMarginNext1: number = grossProfit / revenue;
		const y2workingCapitalPercent =
			(+tradeDebtors + +moneyMultiplierForCeosInputs.reductionInWip - +tradeCreditors) / +revenue;
		const gap2: number = y2GrossMarginNext1 - y2workingCapitalPercent;
		const y2stockDays = (moneyMultiplierForCeosInputs.reductionInWipDays / revenue) * 365;
		const y2creditorDays = (tradeCreditors / lastYearCogs) * 365;
		const cogsReductionImpact = ((y2stockDays - y2creditorDays) / 365) * cogsEbit + cogsEbit;

		dispatchMoneyMultiplierForCeosInputs({
			type: 'EBIT',
			value: +ebit
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'ENDING_MONTH',
			value: month
		});
		dispatchMoneyMultiplierForCeosInputs({
			type: 'ENDING_YEAR',
			value: year
		});
		// total impact net cash flow
		dispatchMoneyMultiplierForCeosInputs({
			type: 'NET_CASH_FLOW_SUM',
			value: Math.round(
				moneyMultiplierForCeosInputs.priceIncreaseNetCashFlow +
					moneyMultiplierForCeosInputs.volumeIncreaseCashFlow +
					moneyMultiplierForCeosInputs.cogsCashFlow +
					moneyMultiplierForCeosInputs.overheadCashFlow +
					moneyMultiplierForCeosInputs.debtorsDayCashFlow +
					moneyMultiplierForCeosInputs.reductionInWip +
					moneyMultiplierForCeosInputs.increaseCreditorsDays +
					moneyMultiplierForCeosInputs.increaseDeferredRevenueDays
			)
		});
		// adjusted position net cash flow
		dispatchMoneyMultiplierForCeosInputs({
			type: 'NET_CASH_FLOW_END',
			value: Math.round(
				+moneyMultiplierForCeosInputs.priceIncreaseNetCashFlow +
					+moneyMultiplierForCeosInputs.volumeIncreaseCashFlow +
					+moneyMultiplierForCeosInputs.cogsCashFlow +
					+moneyMultiplierForCeosInputs.overheadCashFlow +
					+moneyMultiplierForCeosInputs.debtorsDayCashFlow +
					+moneyMultiplierForCeosInputs.reductionInWip +
					+moneyMultiplierForCeosInputs.increaseCreditorsDays +
					+moneyMultiplierForCeosInputs.netCashFlow +
					+moneyMultiplierForCeosInputs.increaseDeferredRevenueDays
			)
		});
		// total impact ebit
		dispatchMoneyMultiplierForCeosInputs({
			type: 'EBIT_SUM',
			value: Math.round(
				+moneyMultiplierForCeosInputs.priceIncreaseEbit +
					+moneyMultiplierForCeosInputs.volumeIncreaseEbit +
					+moneyMultiplierForCeosInputs.cogsEbit +
					+moneyMultiplierForCeosInputs.overheadEbit
			)
		});
		// adjusted position EBIT
		dispatchMoneyMultiplierForCeosInputs({
			type: 'EBIT_END_SUM',
			value: Math.round(
				+moneyMultiplierForCeosInputs.priceIncreaseEbit +
					+moneyMultiplierForCeosInputs.volumeIncreaseEbit +
					+moneyMultiplierForCeosInputs.cogsEbit +
					+moneyMultiplierForCeosInputs.overheadEbit +
					+ebit
			)
		});
		if (beforeLastFinancial && beforeLastFinancial.input !== undefined) {
			const weightAverageEbitda =
				(+ebit +
					+deprecation +
					(+beforeLastFinancial.input.EBIT + +beforeLastFinancial.input.Depreciation)) /
				2;
			const lessTotalDebt: number = +bankLoanCurrent + +bankLoanNonCurrent;
			dispatchMoneyMultiplierForCeosInputs({
				type: 'WEIGHT_AVERAGE_EBITDA',
				value: +weightAverageEbitda
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'LESS_TOTAL_DEBT',
				value: lessTotalDebt
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'EQUITY_VALUATION',
				value: weightAverageEbitda - lessTotalDebt
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'ACTUAL_EQUITY',
				value: totalAssets - totalLiabilities
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'PRICE_INCREASE_IMPACT',
				value: priceIncreaseEbit
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'VOLUME_INCREASE_IMPACT',
				value: volumeIncreaseEbit
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'COGS_IMPACT',
				value: cogsEbit
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'CASH_IMPACT',
				value: debtorsDayCashFlow + reductionInWip + y2creditorDays
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'TOTAL_IMPACT',
				value:
					priceIncreaseEbit +
					volumeIncreaseEbit +
					cogsEbit +
					overheadEbit +
					(debtorsDayCashFlow + reductionInWip + y2creditorDays)
			});
			dispatchMoneyMultiplierForCeosInputs({
				type: 'IMPACT_ON_MULTIPLIER_ADJUSTMENT_ON_VALUATION',
				value:
					priceIncreaseEbit +
					volumeIncreaseEbit +
					cogsEbit +
					overheadEbit +
					(debtorsDayCashFlow + reductionInWip + y2creditorDays)
			});
			// dispatchMoneyMultiplierForCeosInputs({
			// 	type: 'ENHANCED_BUSINESS_VALUE_INDICATOR',
			// 	value:
			// 		weightAverageEbitda * ebitdaValue -
			// 		lessTotalDebt +
			// 		(+lastFinancial.input.Revenue * +priceIncreaseIndex) / 100 +
			// 		+((+lastFinancial.input['Gross Profit'] * +volumeIncreaseIndex) / 100) +
			// 		+((+lastFinancial.input.COGS * +cogsIndex) / 100) +
			// 		+(
			// 			((+lastFinancial.input['Gross Profit'] - +lastFinancial.input.EBIT) *
			// 				+overheadReductionIndex) /
			// 			100
			// 		) *
			// 			ebitdaValue +
			// 		(+lastFinancial.input.Revenue / 365) * debtorsDayReductionIndex +
			// 		+((+lastFinancial.input.Revenue / 365) * reductionWipDaysIndex) +
			// 		+((+lastFinancial.input.COGS / 365) * increaseInCreditorsDaysIndex)
			// });
			dispatchMoneyMultiplierForCeosInputs({
				type: 'ENHANCED_BUSINESS_VALUE_INDICATOR',
				value:
					weightedAverageEBITDA * ebitdaValue -
					lessTotalDebt +
					(+(
						+((+lastFinancial.input.Revenue * +priceIncreaseIndex) / 100) +
						+((+lastFinancial.input['Gross Profit'] * +volumeIncreaseIndex) / 100) +
						+((+lastFinancial.input.COGS * +cogsIndex) / 100) +
						+(
							((+lastFinancial.input['Gross Profit'] - +lastFinancial.input.EBIT) *
								+overheadReductionIndex) /
							100
						)
					) *
						ebitdaValue +
						+(
							+((+lastFinancial.input.Revenue / 365) * debtorsDayReductionIndex) +
							+((+lastFinancial.input.Revenue / 365) * reductionWipDaysIndex) +
							+((+lastFinancial.input.COGS / 365) * increaseInCreditorsDaysIndex)
						))
			});
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [
		dispatchMoneyMultiplierForCeosInputs,
		moneyMultiplierForCeosInputs.priceIncreasePercentEbit,
		moneyMultiplierForCeosInputs.volumeIncreasePercent,
		moneyMultiplierForCeosInputs.cogsPercent,
		moneyMultiplierForCeosInputs.debtorsDayPercentage,
		moneyMultiplierForCeosInputs.overheadPercent,
		moneyMultiplierForCeosInputs.reductionInWipDays,
		moneyMultiplierForCeosInputs.increaseCreditorsDays,
		moneyMultiplierForCeosInputs.increaseInDeferredRevenueDays,
		window.location.reload,
		setSelectedItems,
		selectedItems
	]);

	function planHandler(event: string): void {
		setPlan(event);
		localStorage.setItem('plan', event);
	}

	function companyIdHandler(id: string): void {
		if (!id) return;
		axios
			.post(apiUrl + backendRoutes.financials.get, {
				company_id: id
			})
			.then(({ data }) => {
				if (typeof data !== 'string') {
					setSelectedCompanyFinancials(data);
				}
			});
	}

	function getCompanyTypeHandler(companyType: string) {
		localStorage.setItem('companyType', JSON.stringify(companyType));
	}

	function getCompanySignHandler(event: string) {
		const currency = companyDropdownPredefinedValues.currency.find((item) =>
			item.value === event ? item.label : null
		);
		if (currency) {
			localStorage.setItem('currency', currency.label);
		}
	}

	function demoActiveHandler(event: boolean) {
		setIsDemoActive(event);
	}

	function ebitdaHandler(selectedIndustryId: number) {
		const selectedIndustry = ebitdaMapValues.find((item) => item.id === selectedIndustryId);
		if (selectedIndustry) {
			setSelectedIndustryForEbitda(selectedIndustry as IndustryModel);
		}
	}

	function nextButtonHandler() {
		axios
			.post(apiUrl + backendRoutes.updateSelectedFinancials, {
				selectedFinancials: selectedFinancialsId
			})
			.then((result) => console.log(result));
		setPopupClass(styles.scalePopup);
		setTimeout(() => {
			setPopupClass('');
		}, 1000);
	}

	// eslint-disable-next-line react/jsx-no-constructed-context-values
	const contextValue = {
		editFinancial: editFinancialsHandler,
		financialForEdit,
		selectedItems,
		selectedItemsHandler,
		unselectedItemHandler,
		isCheckedCardHandler,
		whatIsChecked,
		classForPopup,
		financialsPrepHandler,
		storageFinancialsHandler,
		ebit,
		netCashFlow,
		priceIncreaseEbit,
		priceIncreaseNetCashFlow,
		volumeIncrease,
		volumeIncreaseEbit,
		volumeIncreaseCashFlow,
		cogsEbit,
		cogsCashFlow,
		overheadEbit,
		overheadCashFlow,
		debtorsDayCashFlow,
		reductionInWip,
		increaseCreditorsDays,
		netCashFlowSum,
		ebitSum,
		netCashFlowEnd,
		ebitEnd,
		endingMonth,
		endingYear,
		weightedAverageEBITDA,
		equityValuation,
		actualEquity,
		lessTotalDebt,
		setEbitdaHandler,
		ebitdaValue,
		priceIncreaseImpact,
		volumeIncreaseImpact,
		cogsImpact,
		cashImpact,
		totalImpact,
		enhancedBusinessValueIndicator,
		impactOnMultiplierAdjustmentOnValuation,
		getAllStates,
		firstMonth,
		lastMonth,
		firstYear,
		lastYear,
		planHandler,
		plan,
		activateUser,
		activateUserHandler,
		companyIdHandler,
		increaseDeferredRevenueDays,
		selectedCompanyFinancials,
		getCompanyTypeHandler,
		selectedFinancials,
		getCompanySignHandler,
		isDemoActive,
		demoActiveHandler,
		companies,
		profitImpactOnValuation,
		overheadReduction,
		ebitdaHandler,
		selectedIndustryForEbitda,
		nextButtonHandler,
		popupClass,
		loadedSelectedItemsHandler,
		findSelectedFinancials
	};
	return (
		<FinancialsContext.Provider value={contextValue}>{props.children}</FinancialsContext.Provider>
	);
};

export default FinancialsContextProvider;
