import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import environment from '../../../../Environments/environment';
import type { RootState } from '../../../../ReduxState/store';
import { cashFlowProfitabilityCalculator } from '../../../../Store/CashFlowAnalysis/CashFlowSummary/cahs-flow-analysis-context-helper';
import DirectLaborEfficiencyRatioChart from '../../../Dashboard/Components/Profitability/DirectLaborEfficiencyRatioChart';
import type { FinancialsModel } from '../../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import styles from '../../../MoneyForCeos/Components/MoneyForCeosChart.module.scss';
import ProfitabilityTrendsChart from '../../../Dashboard/Components/Profitability/ProfitabilityTrendsChart';
import RevenueVsDirectCostGrowthChart from '../../../Dashboard/Components/Profitability/RevenueVsDirectCostGrowthChart';
import RevenueVsOverheadGrowthChart from '../../../Dashboard/Components/Profitability/RevenueVsOverheadGrowthChart';
import globalStyles from '../../../../Components/GlobalStyles/globals.module.scss';

const CashFlowPerspectiveCharts: React.FC<{ print?: boolean }> = ({
	print
}: {
	print?: boolean;
}): JSX.Element => {
	const { financials } = environment.frontendRoutes;
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);

	const navigate = useNavigate();
	// const history = useHistory();

	useEffect(() => {
		console.log('selectedFinancials', selectedFinancials);
		if (selectedFinancials && selectedFinancials.length < 3) {
			navigate(`${financials}?tool=cashFlowAnalysis`);
		}
	}, [selectedFinancials]);

	const handlePopstate = () => {
		console.log('Navigated back');
		// Add your logic to check selectedFinancials here
		console.log('selectedFinancials', selectedFinancials);
		if (selectedFinancials && selectedFinancials.length < 3) {
			navigate(`${financials}?tool=cashFlowAnalysis`);
		}
	};

	useEffect(() => {
		const localHandlePopstate = handlePopstate;

		window.addEventListener('popstate', localHandlePopstate);

		return () => {
			window.removeEventListener('popstate', localHandlePopstate);
		};
	}, [handlePopstate]);

	const [chartWidth, setChartWidth] = useState<number>(print ? 575 : 798);
	const [chartHeight, setChartHeight] = useState<number>(print ? 385 : 507);
	const [legendHeight, setLegendHeight] = useState<number>(60);
	const [fontSize, setFontSize] = useState<number>(0);
	const [angle, setAngle] = useState<number>(0);

	useEffect(() => {
		if (document.body.offsetWidth < 1000) {
			setChartWidth(document.body.offsetWidth - document.body.offsetWidth / 3);
			setChartHeight(document.body.offsetWidth - document.body.offsetWidth / 2);
			setLegendHeight(document.body.offsetHeight - document.body.offsetHeight / 1.05);
			setFontSize(document.body.offsetWidth < 1000 ? 14 : 16);
			setAngle(document.body.offsetWidth < 1000 ? -10 : 0);
		}
	}, []);

	if (!selectedFinancials || selectedFinancials.length < 3) {
		return <></>;
	}

	const {
		calculatedGrossMarginFirst,
		calculatedGrossMarginSecond,
		calculatedEbitPercentOfRevenueFirst,
		calculatedEbitPercentOfRevenueSecond,
		calculatedNetProfitBeforeTaxOfRevenueFirst,
		calculatedNetProfitBeforeTaxOfRevenueSecond,
		calculatedOverheadsGrowthFirst,
		calculatedOverheadsGrowthSecond,
		calculatedRevenueGrowthSecondFinancial,
		calculatedRevenueGrowthThirdFinancial,
		calculatedCogsGrowthFirst,
		calculatedCogsGrowthSecond
	} = cashFlowProfitabilityCalculator(
		selectedFinancials[0],
		selectedFinancials[1],
		selectedFinancials[2]
	);
	console.log(
		'selectedFinancials',
		selectedFinancials,
		'firstFinancial',
		selectedFinancials[1],
		'secondFinancial',
		selectedFinancials[2]
	);

	console.log('test', {
		name: 'Gross Margin %',
		amt: 100,
		[`${selectedFinancials[1].input['Year Ending']}`]: calculatedGrossMarginFirst.toFixed(2),
		'Ending Year Second Selected Financial': calculatedGrossMarginSecond.toFixed(2)
	});
	const firstSelectedFinancial = selectedFinancials[1];
	const secondSelectedFinancial = selectedFinancials[2];
	const endYearFirstSelectedFinancial = firstSelectedFinancial.input['Year Ending'];
	const endYearSecondSelectedFinancial = secondSelectedFinancial.input['Year Ending'];
	return (
		<div className={`${styles.chartContainer} ${print ? styles.printChartContainer : ''}`}>
			<ProfitabilityTrendsChart mode={print ? 'default' : 'big'} />
			<RevenueVsDirectCostGrowthChart mode={print ? 'default' : 'big'} />
			<RevenueVsOverheadGrowthChart mode={print ? 'default' : 'big'} />
			<div>
				<h3 className={`${globalStyles.title} mt-3 mb-3`}>Direct Labour Productivity</h3>
				<DirectLaborEfficiencyRatioChart embed />
			</div>
		</div>
	);
};

export default CashFlowPerspectiveCharts;
