import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';

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';

const CashFlowPerspectiveChart = (): JSX.Element => {
	const { financials } = environment.frontendRoutes;
	/** NEW */
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);
	/** NEW end */
	// 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 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>(798);
	const [chartHeight, setChartHeight] = useState<number>(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}>
			<ProfitabilityTrendsChart />
			<BarChart
				className={styles.chartContainer__body}
				data={[
					{
						name: 'Gross Margin %',
						amt: 100,
						[`Year ${endYearFirstSelectedFinancial}`]: calculatedGrossMarginFirst.toFixed(2),
						[`Year ${endYearSecondSelectedFinancial}`]: calculatedGrossMarginSecond.toFixed(2)
					},
					{
						name: 'EBIT % of Revenue',
						amt: 100,
						[`Year ${endYearFirstSelectedFinancial}`]:
							calculatedEbitPercentOfRevenueFirst.toFixed(2),
						[`Year ${endYearSecondSelectedFinancial}`]:
							calculatedEbitPercentOfRevenueSecond.toFixed(2)
					},
					{
						name: 'Net Profit (pre tax) % of Revenue',
						amt: 100,
						[`Year ${endYearFirstSelectedFinancial}`]:
							calculatedNetProfitBeforeTaxOfRevenueFirst.toFixed(2),
						[`Year ${endYearSecondSelectedFinancial}`]:
							calculatedNetProfitBeforeTaxOfRevenueSecond.toFixed(2)
					}
				]}
				height={chartHeight}
				margin={{
					top: 5,
					right: 30,
					left: 20,
					bottom: 25
				}}
				width={chartWidth}
			>
				<CartesianGrid strokeDasharray="3 3" />
				<XAxis angle={angle} dataKey="name" fontSize={fontSize} interval={0} tickMargin={15} />
				<YAxis />
				<Tooltip
					cursor={{
						fill: 'var(--primary-color)56'
					}}
				/>
				<Legend height={legendHeight} verticalAlign="top" />
				<Bar dataKey={`Year ${endYearFirstSelectedFinancial}`} fill="#c3c3c4" />
				<Bar dataKey={`Year ${endYearSecondSelectedFinancial}`} fill="var(--primary-color)" />
			</BarChart>

			<h4 className={styles.titleFirstChart}>Revenue Growth vs Direct Costs growth</h4>
			<BarChart
				className={styles.chartContainer__body}
				data={[
					{
						name: `Year ${selectedFinancials[1].input['Year Ending']}`,
						amt: 100,
						'Revenue Growth %': calculatedRevenueGrowthSecondFinancial.toFixed(2),
						'CoGS Growth %': calculatedCogsGrowthFirst.toFixed(2)
					},
					{
						name: `Year ${selectedFinancials[2].input['Year Ending']}`,
						amt: 100,
						'Revenue Growth %': calculatedRevenueGrowthThirdFinancial.toFixed(2),
						'CoGS Growth %': calculatedCogsGrowthSecond.toFixed(2)
					}
				]}
				height={chartHeight}
				margin={{
					top: 5,
					right: 30,
					left: 20,
					bottom: 25
				}}
				width={chartWidth}
			>
				<CartesianGrid strokeDasharray="3 3" />
				<XAxis dataKey="name" interval={0} tickMargin={15} />
				<YAxis />
				<Tooltip
					cursor={{
						fill: 'var(--primary-color)56'
					}}
				/>
				<Legend height={legendHeight} verticalAlign="top" />
				<Bar dataKey="Revenue Growth %" fill="#c3c3c4" />
				<Bar dataKey="CoGS Growth %" fill="var(--primary-color)" />
			</BarChart>

			<h4 className={styles.titleFirstChart}>Revenue Growth vs Direct Costs growth</h4>
			<BarChart
				className={styles.chartContainer__body}
				data={[
					{
						name: 'Revenue Growth',
						amt: 100,
						'Revenue Growth': calculatedRevenueGrowthSecondFinancial.toFixed(2),
						'Overheads Growth': calculatedOverheadsGrowthFirst.toFixed(2)
					},
					{
						name: 'Overheads Growth',
						amt: 100,
						'Revenue Growth': calculatedRevenueGrowthThirdFinancial.toFixed(2),
						'Overheads Growth': calculatedOverheadsGrowthSecond.toFixed(2)
					}
				]}
				height={chartHeight}
				margin={{
					top: 5,
					right: 30,
					left: 20,
					bottom: 25
				}}
				width={chartWidth}
			>
				<CartesianGrid strokeDasharray="3 3" />
				<XAxis dataKey="name" interval={0} tickMargin={15} />
				<YAxis />
				<Tooltip
					cursor={{
						fill: 'var(--primary-color)56'
					}}
				/>
				<Legend height={legendHeight} verticalAlign="top" />
				<Bar dataKey="Revenue Growth" fill="#c3c3c4" />
				<Bar dataKey="Overheads Growth" fill="var(--primary-color)" />
			</BarChart>

			<h4 className={styles.titleFirstChart}>Direct Labour productivity</h4>
			<DirectLaborEfficiencyRatioChart embed />
		</div>
	);
};

export default CashFlowPerspectiveChart;
