// @ts-nocheck
import { useSelector } from 'react-redux';
import {
	ResponsiveContainer,
	ComposedChart,
	Line,
	Scatter,
	XAxis,
	YAxis,
	CartesianGrid,
	Tooltip,
	Customized
} from 'recharts';

import type { RootState } from '../../../../ReduxState/store';
import type { CompanyDbModel } from '../../../Companies/Components/CompaniesComponents.helper';
import type { FinancialsModel } from '../../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import styles from '../../../MoneyForCeos/Components/MoneyForCeosChart.module.scss';
import { moneyForGrowthCalculations } from '../../../../utils/moneyForGrowthCalculations';

const GrowthStrategyChart = (): JSX.Element => {
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const currencyLabel = `${
		typeof selectedCompany?.currency_symbol === 'string'
			? 'GBP'
			: selectedCompany?.currency_symbol.value
	}`;

	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);

	if (!selectedFinancials || selectedFinancials.length < 2) return <></>;
	const { input } = selectedFinancials[selectedFinancials.length - 1];
	// const {
	// 	Revenue,
	// 	EBIT,
	// 	Dividends,
	// 	'Other Income': otherIncome,
	// 	'Interest Paid': interestPaid,
	// 	'Trade Debtors': tradeDebtors,
	// 	Stock,
	// 	'Trade Creditors': tradeCreditors,
	// 	'Deferred Revenue': deferredRevenue,
	// 	'Additional Bank Loans - Current': additionalBankLoansCurrent,
	// 	'Additional Bank Loans - Non Current': additionalBankLoansNonCurrent,
	// 	'Additional Total Assets': additionalTotalAssets,
	// 	'Additional Total Liabilities': additionalTotalLiabilities
	// } = input;
	// const increasedRevenueUpdated = 100;

	// const calculatedEbit = (+EBIT / +Revenue) * increasedRevenueUpdated;
	// const calculatedLessOtherIncome = (+otherIncome / +Revenue) * increasedRevenueUpdated;
	// const calculatedLessInterest = (+interestPaid / +Revenue) * increasedRevenueUpdated;

	// const calculatedNetProfitPreTax =
	// 	calculatedEbit + calculatedLessOtherIncome - calculatedLessInterest;

	// const calculatedWorkingCapitalOf =
	// 	((+tradeDebtors + +Stock - +tradeCreditors - +deferredRevenue) / +Revenue) *
	// 	increasedRevenueUpdated;

	// const calculatedLessTax =
	// 	((+EBIT - +input['Interest Paid'] + +input['Other Income'] - +input['Net Profit']) / +Revenue) *
	// 	increasedRevenueUpdated;
	// const calculatedLessDividends = (+Dividends / +Revenue) * increasedRevenueUpdated;
	// const calculatedRetainedProfit =
	// 	+calculatedEbit +
	// 	calculatedLessOtherIncome -
	// 	calculatedLessInterest -
	// 	calculatedLessTax -
	// 	calculatedLessDividends;
	// const calculatedDebtToEquityRatio =
	// 	(+additionalBankLoansCurrent + +additionalBankLoansNonCurrent) /
	// 	(+additionalTotalAssets - +additionalTotalLiabilities);
	// const calculatedBorrowMoney = calculatedRetainedProfit * calculatedDebtToEquityRatio;
	const calculated = moneyForGrowthCalculations(input, 100);
	const {
		borrowMoney: calculatedBorrowMoney,
		requiredWorkingCapital,
		cashFlowOnGrowth,
		preTaxProfit
	} = calculated;

	const xVal = requiredWorkingCapital;
	const xValFormatted = xVal.toLocaleString('en-GB', {
		style: 'currency',
		currency: currencyLabel,
		minimumFractionDigits: 2,
		maximumFractionDigits: 2
	});
	const yVal = preTaxProfit;
	const yValFormatted = yVal.toLocaleString('en-GB', {
		style: 'currency',
		currency: currencyLabel,
		minimumFractionDigits: 2,
		maximumFractionDigits: 2
	});

	// const cashFlowOnGrowth = calculatedNetProfitPreTax - calculatedWorkingCapitalOf;
	// hardcoded at client request
	const cashFlowOnGrowthLabel = 'linear growth';
	// cashFlowOnGrowth > 0 ? 'You can grow without burning cash' : 'Your growth will burn cash';
	// hardcoded at client request
	const borrowMoneyLabel = 'zig-zag growth';
	// +calculatedBorrowMoney > 0 ? 'Linear growth' : 'Grow then pause, then grow again';

	// Calculate 10% buffer for axes
	const xMax = Math.round(xVal * 1.1); // 38.5
	const yMax = Math.round(yVal * 1.1); // 44

	const axisPositive = Math.max(Math.abs(xMax), Math.abs(yMax));
	const axisNegative = -1 * axisPositive;

	// Diagonal line data: full-length from origin to end of x-axis
	const diagonalData = [
		{ x: axisNegative, y: axisNegative },
		{ x: axisPositive, y: axisPositive }
	];

	// Updated actual growth point
	const actualData = [{ x: xVal.toFixed(2), y: yVal.toFixed(2) }];

	// Text annotations positioned in data coordinates
	const annotations = [
		{ x: xMax / 2.2, y: yMax / 1.7, text: cashFlowOnGrowthLabel },
		{ x: xMax / 1.5, y: yMax / 2.3, text: borrowMoneyLabel }
	];

	return (
		<div>
			<h3 className={styles.title}>Growth Strategy</h3>

			<ResponsiveContainer width="100%" height={330}>
				<ComposedChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
					<CartesianGrid stroke="#eee" />

					<XAxis
						type="number"
						dataKey="x"
						domain={[0, xMax]}
						tickCount={8}
						tickFormatter={(val) => `£${val}`}
						label={{
							value: `Working capital per 100 ${selectedCompany?.currency_symbol.value} sale`,
							position: 'insideBottom',
							offset: -10,
							style: { fontSize: 12, fill: '#000' },
							dy: 5
						}}
					/>

					{console.log('yMax', yMax)}
					<YAxis
						type="number"
						dataKey="y"
						domain={[0, yMax]}
						tickCount={9}
						tickFormatter={(val) => `£${val}`}
						label={{
							value: `Net Profit (pre-tax) per 100 ${selectedCompany?.currency_symbol.value} sale`,
							angle: -90,
							position: 'insideLeft',
							style: { fontSize: 12, fill: '#000' },
							dy: 90
						}}
					/>

					<Tooltip formatter={(value) => [`£${value}`]} />

					{/* Diagonal line splitting into two triangles */}

					<Line type="linear" data={diagonalData} dataKey="y" stroke="#1f77b4" dot={false} />

					{/* Actual data point */}

					<Scatter data={actualData} dataKey="y" fill="#ff7f0e" />

					{/* Annotations */}

					<Customized
						component={({ xAxisMap, yAxisMap }) =>
							annotations.map((ann, i) => {
								const xScale = xAxisMap['0'].scale;

								const yScale = yAxisMap['0'].scale;

								return (
									<text
										key={i}
										x={xScale(ann.x)}
										y={yScale(ann.y)}
										fill="#444"
										fontSize={12}
										textAnchor="middle"
									>
										{ann.text}
									</text>
								);
							})
						}
					/>
				</ComposedChart>
			</ResponsiveContainer>
		</div>
	);
};

export default GrowthStrategyChart;
