/* eslint-disable @typescript-eslint/no-unused-vars */
import type { ReactNode } from 'react';
import type React from 'react';
import { createContext, useContext, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import selectDashboardChartsHelper from '../../Pages/Dashboard/Pages/DashboardSelect/dashboard-select-chart.helper';
import type { FinancialsModel } from '../../Pages/Financials/Components/FinancialsForm/FinancialsForm.helper';
import type { RootState } from '../../ReduxState/store';
import cashFlowAnalysisPerspectiveCalculationsHelper from '../CashFlowAnalysis/CashFlowPerspective/cashFlowPerspective-context-helper';
import type { GlobalStateModel } from '../global/GlobalState-context';
import { GlobalStateContext } from '../global/GlobalState-context';

export type DashboardContextModel = {
	addElementsHandler: (element: string) => void;
	removeElementsHandler: (element: string) => void;
	selectedCharts: string[];
	netProfitPreTaxChange: number;
	netOperatingAssetsChange: number;
	returnOnAssetsChange: number;
	returnOnAssetsSecond: number;
	returnOnEquityChange: number;
	returnOnEquitySecond: number;
	operatingCashProfit: string;
	funding: string;
	operatingCashFlow: string;
	netDebt: string;
	debtToEquitySecond: string;
	debtToEquityChange: string;
	lessTax: string;
	lessDividend: string;
	retainedProfit: string;
	shortfall: string;
	dashboardCalculationsHandler: () => void;
	changeInputCheckbox: (event: string) => void;
	switchToPage: boolean;
	checkProfitability: boolean;
	checkRevenueGrowth: boolean;
	checkDirectLabourEfficiencyRatio: boolean;
	checkWorkingCapitalTimeline: boolean;
	checkWorkingCapital: boolean;
	checkMarginalCashflow: boolean;
	checkReturnInvestedCapital: boolean;
	checkReturnTotalAssets: boolean;
	checkReturnEquity: boolean;
	checkOperatingCashProfit: boolean;
	checkOperatingCashFlow: boolean;
	checkYourFunding: boolean;
	checkDebtToEquity: boolean;
	checkNetDebt: boolean;
	checkNetProfitPreTax: boolean;
	checkMFGSurplusShortfall: boolean;
	checkGrowthStrategy: boolean;
	checkNetCashFlow: boolean;
	checkEbitOperatingProfit: boolean;
	checkMMFCeosEffectOnNetCashFlowAndEbit: boolean;
	checkMMFCeosEffectOnYourBusinessValue: boolean;
	reloadHandler: () => void;
};

export const DashboardContext: React.Context<DashboardContextModel> =
	createContext<DashboardContextModel>({
		addElementsHandler: () => {},
		removeElementsHandler: () => {},
		selectedCharts: [],
		netOperatingAssetsChange: 0,
		netProfitPreTaxChange: 0,
		returnOnAssetsChange: 0,
		returnOnAssetsSecond: 0,
		returnOnEquityChange: 0,
		returnOnEquitySecond: 0,
		operatingCashProfit: '',
		funding: '',
		operatingCashFlow: '',
		netDebt: '',
		debtToEquitySecond: '',
		debtToEquityChange: '',
		lessTax: '',
		lessDividend: '',
		retainedProfit: '',
		shortfall: '',
		dashboardCalculationsHandler: (): void => {},
		changeInputCheckbox: (): void => {},
		reloadHandler: (): void => {},
		switchToPage: false,
		checkRevenueGrowth: false,
		checkDirectLabourEfficiencyRatio: false,
		checkWorkingCapitalTimeline: false,
		checkWorkingCapital: false,
		checkMarginalCashflow: false,
		checkReturnInvestedCapital: false,
		checkReturnTotalAssets: false,
		checkReturnEquity: false,
		checkOperatingCashProfit: false,
		checkOperatingCashFlow: false,
		checkYourFunding: false,
		checkDebtToEquity: false,
		checkNetDebt: false,
		checkNetProfitPreTax: false,
		checkMFGSurplusShortfall: false,
		checkGrowthStrategy: false,
		checkNetCashFlow: false,
		checkEbitOperatingProfit: false,
		checkMMFCeosEffectOnNetCashFlowAndEbit: false,
		checkMMFCeosEffectOnYourBusinessValue: false,
		checkProfitability: false
	});

const DashboardContextProvider: React.FC<{ children: ReactNode }> = (props: {
	children: ReactNode;
}) => {
	/** NEW start */
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);
	// console.log('from dashboard context', selectedFinancials);
	useEffect(() => {
		if (!selectedFinancials) {
			return;
		}
		// const firstFinancial: FinancialsModel = selectedFinancials[0];
		// const secondFinancial: FinancialsModel = selectedFinancials[1];
		// const thirdFinancial: FinancialsModel = selectedFinancials[2];

		// window.scrollTo(0, 0);
		dashboardCalculationsHandler();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectedFinancials]);
	/** NEW end */
	const [selectedCharts, setSelectedCharts] = useState<string[]>([]);
	const [netOperatingAssetsChange, setNetOperatingAssetsChange] = useState<number>(0);
	const [netProfitPreTaxChange, setNetProfitPreTaxChange] = useState<number>(0);
	const [returnOnAssetsChange, setReturnOnAssetsChange] = useState<number>(0);
	const [returnOnAssetsSecond, setReturnOnAssetsSecond] = useState<number>(0);
	const [returnOnEquityChange, setReturnOnEquityChange] = useState<number>(0);
	const [returnOnEquitySecond, setReturnOnEquitySecond] = useState<number>(0);
	const [operatingCashProfit, setOperatingCashProfit] = useState<string>('');
	const [funding, setFunding] = useState<string>('');
	const [operatingCashFlow, setOperatingCashFlow] = useState<string>('');
	const [netDebt, setNetDebt] = useState<string>('');
	const [debtToEquitySecond, setDebtToEquitySecond] = useState<string>('');
	const [debtToEquityChange, setDebtToEquityChange] = useState<string>('');
	const [lessTax, setLessTax] = useState<string>('');
	const [lessDividend, setLessDividend] = useState<string>('');
	const [retainedProfit, setRetainedProfit] = useState<string>('');
	const [shortfall, setShortfall] = useState<string>('');
	const [switchToPage, setSwitchToPage] = useState<boolean>(false);
	const [checkProfitability, setCheckProfitability] = useState<boolean>(false);
	const [checkRevenueGrowth, setCheckRevenueGrowth] = useState<boolean>(false);
	const [checkDirectLabourEfficiencyRatio, setCheckDirectLabourEfficiencyRatio] =
		useState<boolean>(false);
	const [checkWorkingCapitalTimeline, setCheckWorkingCapitalTimeline] = useState<boolean>(false);
	const [checkWorkingCapital, setCheckWorkingCapital] = useState<boolean>(false);
	const [checkMarginalCashflow, setCheckMarginalCashflow] = useState<boolean>(false);
	const [checkReturnInvestedCapital, setCheckReturnInvestedCapital] = useState<boolean>(false);
	const [checkReturnTotalAssets, setCheckReturnTotalAssets] = useState<boolean>(false);
	const [checkReturnEquity, setCheckReturnEquity] = useState<boolean>(false);
	const [checkOperatingCashProfit, setCheckOperatingCashProfit] = useState<boolean>(false);
	const [checkOperatingCashFlow, setCheckOperatingCashFlow] = useState<boolean>(false);
	const [checkYourFunding, setCheckYourFunding] = useState<boolean>(false);
	const [checkDebtToEquity, setCheckDebtToEquity] = useState<boolean>(false);
	const [checkNetDebt, setCheckNetDebt] = useState<boolean>(false);
	const [checkNetProfitPreTax, setCheckNetProfitPreTax] = useState<boolean>(false);
	const [checkMFGSurplusShortfall, setCheckMFGSurplusShortfall] = useState<boolean>(false);
	const [checkGrowthStrategy, setCheckGrowthStrategy] = useState<boolean>(false);
	const [checkNetCashFlow, setCheckNetCashFlow] = useState<boolean>(false);
	const [checkEbitOperatingProfit, setCheckEbitOperatingProfit] = useState<boolean>(false);
	const [checkMMFCeosEffectOnNetCashFlowAndEbit, setCheckMMFCeosEffectOnNetCashFlowAndEbit] =
		useState<boolean>(false);
	const [checkMMFCeosEffectOnYourBusinessValue, setCheckMMFCeosEffectOnYourBusinessValue] =
		useState<boolean>(false);
	const listOfSelectedChartsFromStorage: string[] = JSON.parse(
		localStorage.getItem('selected-dashboard-charts') as string
	);
	const globalContext: GlobalStateModel = useContext(GlobalStateContext);

	function addElementsHandler(item: string): void {
		setSelectedCharts((prevState) => {
			globalContext.saveSelectedDashboardCharts([...prevState, item]);
			localStorage.setItem('selected-dashboard-charts', JSON.stringify([...prevState, item]));
			return [...prevState, item];
		});
	}

	function removeElementsHandler(event: string): void {
		setSelectedCharts((prevState) => {
			const filteredCharts = prevState.filter((item) => item !== event);
			localStorage.setItem('selected-dashboard-charts', JSON.stringify(filteredCharts));
			globalContext.saveSelectedDashboardCharts(filteredCharts);
			return filteredCharts;
		});
	}

	function changeInputCheckbox(event: string): void {
		switch (event) {
			case selectDashboardChartsHelper[0].name:
				return setCheckProfitability(!checkProfitability);

			case selectDashboardChartsHelper[1].name:
				return setCheckRevenueGrowth(!checkRevenueGrowth);

			case selectDashboardChartsHelper[2].name:
				return setCheckDirectLabourEfficiencyRatio(!checkDirectLabourEfficiencyRatio);

			case selectDashboardChartsHelper[3].name:
				return setCheckWorkingCapitalTimeline(!checkWorkingCapitalTimeline);

			case selectDashboardChartsHelper[4].name:
				return setCheckWorkingCapital(!checkWorkingCapital);

			case selectDashboardChartsHelper[5].name:
				return setCheckMarginalCashflow(!checkMarginalCashflow);

			case selectDashboardChartsHelper[6].name:
				return setCheckReturnInvestedCapital(!checkReturnInvestedCapital);

			case selectDashboardChartsHelper[7].name:
				return setCheckReturnTotalAssets(!checkReturnTotalAssets);

			case selectDashboardChartsHelper[8].name:
				return setCheckReturnEquity(!checkReturnEquity);

			case selectDashboardChartsHelper[9].name:
				return setCheckOperatingCashProfit(!checkOperatingCashProfit);

			case selectDashboardChartsHelper[12].name:
				return setCheckOperatingCashFlow(!checkOperatingCashFlow);

			case selectDashboardChartsHelper[10].name:
				return setCheckYourFunding(!checkYourFunding);

			case selectDashboardChartsHelper[11].name:
				return setCheckDebtToEquity(!checkDebtToEquity);

			case selectDashboardChartsHelper[13].name:
				return setCheckNetDebt(!checkNetDebt);

			case selectDashboardChartsHelper[14].name:
				return setCheckNetProfitPreTax(!checkNetProfitPreTax);

			case selectDashboardChartsHelper[15].name:
				return setCheckMFGSurplusShortfall(!checkMFGSurplusShortfall);

			case selectDashboardChartsHelper[16].name:
				return setCheckGrowthStrategy(!checkGrowthStrategy);

			case selectDashboardChartsHelper[17].name:
				return setCheckNetCashFlow(!checkNetCashFlow);

			case selectDashboardChartsHelper[18].name:
				return setCheckEbitOperatingProfit(!checkEbitOperatingProfit);

			case selectDashboardChartsHelper[19].name:
				return setCheckMMFCeosEffectOnNetCashFlowAndEbit(!checkMMFCeosEffectOnNetCashFlowAndEbit);

			case selectDashboardChartsHelper[20].name:
				return setCheckMMFCeosEffectOnYourBusinessValue(!checkMMFCeosEffectOnYourBusinessValue);

			default:
				return (
					setCheckProfitability(false),
					setCheckRevenueGrowth(false),
					setCheckDirectLabourEfficiencyRatio(false),
					setCheckWorkingCapitalTimeline(false),
					setCheckWorkingCapital(false),
					setCheckMarginalCashflow(false),
					setCheckReturnInvestedCapital(false),
					setCheckReturnTotalAssets(false),
					setCheckReturnEquity(false),
					setCheckOperatingCashProfit(false),
					setCheckOperatingCashFlow(false),
					setCheckYourFunding(false),
					setCheckDebtToEquity(false),
					setCheckNetDebt(false),
					setCheckNetProfitPreTax(false),
					setCheckMFGSurplusShortfall(false),
					setCheckGrowthStrategy(false),
					setCheckNetCashFlow(false),
					setCheckEbitOperatingProfit(false),
					setCheckMMFCeosEffectOnNetCashFlowAndEbit(false)
				);
		}
	}

	useEffect(() => {
		if (listOfSelectedChartsFromStorage) {
			listOfSelectedChartsFromStorage.forEach((item) => changeInputCheckbox(item));
			setSelectedCharts(listOfSelectedChartsFromStorage);
		}
		if (!listOfSelectedChartsFromStorage) {
			const allCharts = selectDashboardChartsHelper.map((item) => item.name);
			setSelectedCharts(allCharts);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	function reloadHandler(): void {
		setSelectedCharts(JSON.parse(localStorage.getItem('selected-dashboard-charts') as string));
	}

	const selectedPage = JSON.parse(localStorage.getItem('selected-financials') as string);

	function dashboardCalculationsHandler() {
		console.log('IN dashboardCalculationsHandler');
		// 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
		// );
		if (!selectedFinancials) {
			return;
		}
		const firstFinancial: FinancialsModel = selectedFinancials[0];
		const secondFinancial: FinancialsModel = selectedFinancials[1];
		const thirdFinancial: FinancialsModel = selectedFinancials[2];
		console.log('IN dashboardCalculationsHandler', firstFinancial, secondFinancial, thirdFinancial);
		if (!firstFinancial) {
			return;
		}
		const calculatedLessTax =
			((+firstFinancial.input.EBIT -
				+firstFinancial.input['Interest Paid'] +
				+firstFinancial.input['Other Income'] -
				+firstFinancial.input['Net Profit']) /
				+firstFinancial.input.Revenue) *
			100;
		const calculatedLessDividends =
			(+firstFinancial.input.Dividends / +firstFinancial.input.Revenue) * 100;
		const calculatedEbit = (+firstFinancial.input.EBIT / +firstFinancial.input.Revenue) * 100;
		const calculatedLessOtherIncome =
			(+firstFinancial.input['Other Income'] / +firstFinancial.input.Revenue) * 100;
		const calculatedLessInterest =
			(+firstFinancial.input['Interest Paid'] / +firstFinancial.input.Revenue) * 100;
		const calculatedRetainedProfit =
			+calculatedEbit +
			+calculatedLessOtherIncome -
			+calculatedLessInterest -
			+calculatedLessTax -
			+calculatedLessDividends;
		setLessTax(calculatedLessTax.toFixed(2));
		setLessDividend(calculatedLessDividends.toFixed(2));
		const calculatedNetProfitPreTax =
			calculatedEbit + calculatedLessOtherIncome - calculatedLessInterest;
		const calculatedWorkingCapitalOf =
			((+firstFinancial.input['Trade Debtors'] +
				+firstFinancial.input.Stock -
				+firstFinancial.input['Trade Creditors'] -
				+firstFinancial.input['Deferred Revenue']) /
				+firstFinancial.input.Revenue) *
			100;
		setRetainedProfit(calculatedRetainedProfit.toFixed(2).toString());
		setShortfall((calculatedNetProfitPreTax - calculatedWorkingCapitalOf).toFixed(2));
		if (!secondFinancial || !thirdFinancial) {
			return;
		}
		const calculatedRevenue = +thirdFinancial.input.Revenue;
		const directCostDefined = +thirdFinancial.input.COGS;
		const calculatedGrossMargin = +calculatedRevenue - +directCostDefined;
		const calculatedOverheadsExcluded =
			+thirdFinancial.input['Gross Profit'] -
			+thirdFinancial.input.EBIT -
			+thirdFinancial.input.Depreciation;

		const calculatedOperatingCashProfit = (
			+calculatedGrossMargin - +calculatedOverheadsExcluded
		).toString();
		const calculatedCashFromCustomersVariance =
			+secondFinancial.input['Trade Debtors'] - +thirdFinancial.input['Trade Debtors'];
		const calculatedCashFromCustomers = calculatedRevenue + calculatedCashFromCustomersVariance;
		const calculatedCashToSuppliersVariance =
			+secondFinancial.input['Trade Creditors'] -
			+thirdFinancial.input['Trade Creditors'] +
			(+secondFinancial.input.Stock - +thirdFinancial.input.Stock);
		const calculatedCashToSuppliers = directCostDefined + calculatedCashToSuppliersVariance;
		const calculatedGrossProfit = +calculatedCashFromCustomers - +calculatedCashToSuppliers;
		const calculatedCashFlowSecond =
			-(
				+secondFinancial.input['Cash at Bank'] -
				(+secondFinancial.input['Additional Bank Loans - Current'] +
					+secondFinancial.input['Additional Bank Loans - Non Current'])
			) -
			-(
				+thirdFinancial.input['Cash at Bank'] -
				(+thirdFinancial.input['Additional Bank Loans - Current'] +
					+thirdFinancial.input['Additional Bank Loans - Non Current'])
			);
		const calculatedOperatingCashFlow = +calculatedGrossProfit - +calculatedOverheadsExcluded;
		const calculatedNetDebtSecond =
			+thirdFinancial.input['Additional Bank Loans - Current'] +
			+thirdFinancial.input['Additional Bank Loans - Non Current'] -
			+thirdFinancial.input['Cash at Bank'];
		const calculatedDebtToEquityFirst =
			(+secondFinancial.input['Additional Bank Loans - Current'] +
				+secondFinancial.input['Additional Bank Loans - Non Current']) /
			(+secondFinancial.input['Additional Total Assets'] -
				+secondFinancial.input['Additional Total Liabilities']);
		const calculatedDebtToEquitySecond =
			+thirdFinancial.input['Additional Bank Loans - Current'] +
			+thirdFinancial.input['Additional Bank Loans - Non Current'] /
				(+thirdFinancial.input['Additional Total Assets'] -
					+thirdFinancial.input['Additional Total Liabilities']);
		const calculatedDebtToEquityChange =
			calculatedDebtToEquitySecond === 0 || calculatedDebtToEquityFirst === 0
				? 0
				: ((calculatedDebtToEquitySecond - +calculatedDebtToEquityFirst) /
						+calculatedDebtToEquityFirst) *
				  100;
		const {
			calculatedReturnOnTotalAssetsSecond,
			calculatedReturnOnTotalAssetsChange,
			calculatedReturnOnEquitySecond,
			calculatedReturnOnEquityChange,
			calculatedNetOperatingAssetsChange,
			calculatedNetProfitPreTaxChange
		} = cashFlowAnalysisPerspectiveCalculationsHelper(secondFinancial, thirdFinancial);
		setNetOperatingAssetsChange(calculatedNetOperatingAssetsChange);
		setNetProfitPreTaxChange(calculatedNetProfitPreTaxChange);
		setReturnOnAssetsChange(calculatedReturnOnTotalAssetsChange);
		setReturnOnEquityChange(calculatedReturnOnEquityChange);
		setReturnOnEquitySecond(calculatedReturnOnEquitySecond);
		setReturnOnAssetsSecond(calculatedReturnOnTotalAssetsSecond);

		setOperatingCashProfit(calculatedOperatingCashProfit.toString());
		setFunding(calculatedCashFlowSecond.toString());
		setOperatingCashFlow(calculatedOperatingCashFlow.toString());
		setNetDebt(calculatedNetDebtSecond.toString());
		setDebtToEquitySecond(calculatedDebtToEquitySecond.toString());
		setDebtToEquityChange(calculatedDebtToEquityChange.toString());
	}

	useEffect(() => {
		dashboardCalculationsHandler();
	}, [selectedPage]);

	// eslint-disable-next-line react/jsx-no-constructed-context-values
	const contextValue = {
		addElementsHandler,
		removeElementsHandler,
		selectedCharts,
		netOperatingAssetsChange,
		netProfitPreTaxChange,
		returnOnAssetsChange,
		returnOnAssetsSecond,
		returnOnEquityChange,
		returnOnEquitySecond,
		operatingCashProfit,
		funding,
		operatingCashFlow,
		netDebt,
		debtToEquitySecond,
		debtToEquityChange,
		lessTax,
		lessDividend,
		retainedProfit,
		shortfall,
		dashboardCalculationsHandler,
		switchToPage,
		changeInputCheckbox,
		checkRevenueGrowth,
		checkDirectLabourEfficiencyRatio,
		checkWorkingCapitalTimeline,
		checkWorkingCapital,
		checkMarginalCashflow,
		checkReturnInvestedCapital,
		checkReturnTotalAssets,
		checkReturnEquity,
		checkOperatingCashProfit,
		checkOperatingCashFlow,
		checkYourFunding,
		checkDebtToEquity,
		checkNetDebt,
		checkNetProfitPreTax,
		checkMFGSurplusShortfall,
		checkGrowthStrategy,
		checkNetCashFlow,
		checkEbitOperatingProfit,
		checkMMFCeosEffectOnNetCashFlowAndEbit,
		checkMMFCeosEffectOnYourBusinessValue,
		checkProfitability,
		reloadHandler
	};
	return (
		// eslint-disable-next-line react/destructuring-assignment
		<DashboardContext.Provider value={contextValue}>{props.children}</DashboardContext.Provider>
	);
};

export default DashboardContextProvider;
