/* eslint-disable react/destructuring-assignment */
import type React from 'react';
import { useContext, useDeferredValue, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import type { RootState } from '../../../ReduxState/store';
import type { MoneyGrowContextModel } from '../../../Store/MoneyForGrowth/MoneyForGrowth-Contex';
import { MoneyGrowthContext } from '../../../Store/MoneyForGrowth/MoneyForGrowth-Contex';
import type { CompanyDbModel } from '../../Companies/Components/CompaniesComponents.helper';
import type {
	FinancialsInterface,
	FinancialsModel
} from '../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import ArrowDownMoneyForGrowth from './ArrowDownMoneyForGrowth';
import { moneyForGrowthCalculations } from '../../../utils/moneyForGrowthCalculations';
import type { FinancialData } from '../../../utils/moneyForGrowthCalculations';
import { useNavigate } from 'react-router-dom';
import styles from './MoneyForGrowthList.module.scss';
import { FundingMeters } from '../../../Store/CashFlowAnalysis/FundingMeters/FundingMeters-context';
import type { FundingMetersModel } from '../../../Store/CashFlowAnalysis/FundingMeters/FundingMeters-context';

interface MoneyList {
	listContainer: string;
	darkerList: string;
	arrowLines: string;
	arrowLinesOnly: string;
	arrowsContainer: string;
	verticalLine: string;
	splitListContainer: string;
	normalRow: string;
	singleSplitColumn: string;
	revenue: number;
}

const MoneyForGrowthList: React.FC<MoneyList> = (props: MoneyList): JSX.Element => {
	const moneyGrowthContext: MoneyGrowContextModel = useContext(MoneyGrowthContext);
	const fundingContext: FundingMetersModel = useContext(FundingMeters);
	const [grossProfit, setGrossProfit] = useState<number>(0);
	const [lessOverheads, setLessOverheads] = useState<number>(0);
	const [lessCogs, setLessCogs] = useState<number>(0);
	const [earningsBeforeTax, setEarningsBeforeTax] = useState<number>(0);
	const [lessOtherIncome, setLessOtherIncome] = useState<number>(0);
	const [lessInterest, setLessInterest] = useState<number>(0);
	const [lessTax, setLessTax] = useState<number>(0);
	const [lessDividend, setLessDividend] = useState<number>(0);
	const [retainedProfit, setRetainedProfit] = useState<number>(0);
	const [requiredWorkingCapital, setRequiredWorkingCapital] = useState<number>(0);
	const [preTaxProfit, setPreTaxProfit] = useState<number>(0);
	const [cashFlowOnGrowth, setCashFlowOnGrowth] = useState<number>(0);
	const [borrowMoney, setBorrowMoney] = useState<number>(0);
	const [debtToEquityRatio, setDebtToEquityRatio] = useState<number>(0);
	const [shortfall, setShortfall] = useState<number>(0);
	const [banksLendFromEbitda, setBanksLendFromEbitda] = useState<number>(0);
	const navigate = useNavigate();
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const currencyLabel = `${
		typeof selectedCompany?.currency_symbol === 'string'
			? 'GBP'
			: selectedCompany?.currency_symbol.value
	}`;

	const firstFinancial = useDeferredValue(
		JSON.parse(localStorage.getItem('first-financial') as string)
	);

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

	if (!selectedFinancials || selectedFinancials.length === 0) {
		navigate('/financials');
		return <></>;
	}

	// const { input } = selectedFinancials[0];
	// use the most recent financial data in pool of selected financials
	// i.e. if the user has selected 3 financials, then the most recent financial data is the third financial
	// given that the first financial is the oldest financial
	const { input } = selectedFinancials[selectedFinancials.length - 1];
	console.log('input', input);
	const { COGS, Revenue, EBIT, Dividends } = input;
	// const { increasedRevenueUpdated } = moneyGrowthContext;
	const { revenue: increasedRevenueUpdated } = props;
	/** NEW end */
	// will be needed only if negative cash flow on growth:
	const [fundingReqiredMonths, setFundingReqiredMonths] = useState<string | number>(0);

	const runwayRounded = (input: FinancialsInterface, calculations: FinancialData) => {
		const runway = Math.abs(
			+input['Cash at Bank'] /
				((+fundingContext.calculatedCashFlowSecond + +calculations.cashFlowOnGrowth) / 12)
		);
		console.log(
			'runway',
			runway,
			input['Cash at Bank'],
			fundingContext.calculatedCashFlowSecond,
			calculations.cashFlowOnGrowth
		);
		const decimalPart = runway - Math.floor(runway);

		if (runway > 12) {
			return '12+';
		}

		if (decimalPart < 0.5) {
			return Math.floor(runway);
		}
		return runway.toFixed(2);
	};

	useEffect(() => {
		const calculations = moneyForGrowthCalculations(input, increasedRevenueUpdated);
		setGrossProfit(calculations.grossProfit);
		setLessCogs(calculations.lessCogs);
		setLessOverheads(calculations.lessOverheads);
		setEarningsBeforeTax(calculations.calculatedEbit);
		setLessOtherIncome(calculations.lessOtherIncome);
		setLessTax(calculations.lessTax);
		setLessInterest(calculations.lessInterest);
		setLessDividend(calculations.lessDividend);
		setRetainedProfit(calculations.retainedProfit);
		setShortfall(calculations.shortfall);
		setBanksLendFromEbitda(calculations.banksLendFromEbitda);
		setRequiredWorkingCapital(calculations.requiredWorkingCapital);
		setCashFlowOnGrowth(calculations.cashFlowOnGrowth);
		setBorrowMoney(calculations.borrowMoney);
		setDebtToEquityRatio(calculations.debtToEquityRatio);
		setPreTaxProfit(calculations.preTaxProfit);
		setFundingReqiredMonths(runwayRounded(input, calculations));
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [increasedRevenueUpdated, COGS, Revenue, EBIT, fundingContext]);

	useEffect(() => {
		moneyGrowthContext.updateFinancialHandler(firstFinancial as FinancialsModel);
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<div className={props.listContainer}>
			<div className={props.normalRow}>
				<ul>
					<h4 className={styles.tableHeading}>
						<b>Gross Margin</b>
					</h4>
					<ArrowDownMoneyForGrowth />
					<li>
						<p>(Less CoGS)</p>
						<p>
							{lessCogs.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
					<li>
						<p>Gross margin</p>
						<p>
							{grossProfit.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
				</ul>
				<ul>
					<h4 className={styles.tableHeading}>
						<b>EBIT</b>
					</h4>
					<ArrowDownMoneyForGrowth />
					<li>
						<p>(Less Overheads)</p>
						<p>
							{lessOverheads.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
					<li>
						<p>Earnings before income & tax</p>
						<p>
							{earningsBeforeTax.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
				</ul>
				<ul>
					<h4 className={styles.tableHeading}>
						<b>Profitability</b>
					</h4>
					<ArrowDownMoneyForGrowth />
					<li>
						<p>(Less Other Income)</p>
						<p>
							{lessOtherIncome.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
					<li>
						<p>(Less Interest)</p>
						<p>
							{lessInterest.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
					<li>
						<p>
							<b>Profit (pre-tax)</b>
						</p>
						<p>
							<b>
								{preTaxProfit.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</b>
						</p>
					</li>
					<li>
						<p>(Less Tax)</p>
						<p>
							{lessTax.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
					<li>
						<p>(Less Dividend)</p>
						<p>
							{lessDividend.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
					<li>
						<p>
							<b>The retained profit will be</b>
						</p>
						<p>
							<b>
								{retainedProfit.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</b>
						</p>
					</li>
				</ul>
				<ul>
					<h4 className={styles.tableHeading}>
						<b>Funding Needs</b>
					</h4>
					<ArrowDownMoneyForGrowth />
					<li className={styles.middleRow}>
						<p>Required working capital</p>
						<p>
							{' '}
							{requiredWorkingCapital.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 2,
								maximumFractionDigits: 2
							})}
						</p>
					</li>
				</ul>
				<div className={props.verticalLine} />
				<div className={props.arrowLines} />

				<ul>
					<li className={styles.middleRow}>
						<p style={{ marginLeft: '54px', marginBottom: '0' }}>Funding pathways</p>
						<p style={{ marginRight: '56px', marginBottom: '0' }}>Growth strategy</p>
					</li>
				</ul>
				<div className={props.arrowLinesOnly} />
				<div className={props.arrowsContainer}>
					<ArrowDownMoneyForGrowth />
					<ArrowDownMoneyForGrowth />
				</div>
			</div>
			<div className={props.splitListContainer}>
				<div className={props.singleSplitColumn}>
					<ul className={props.darkerList}>
						<h4 className={styles.tableHeading}>
							<b>Surplus / Shortfall</b>
						</h4>
						<li>
							<p>{shortfall > 0 ? 'Surplus' : 'Shortfall'}</p>
							<p>
								{shortfall.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</p>
						</li>
					</ul>
					<ul className={props.darkerList}>
						<h4 style={{ textTransform: 'none' }}>
							<b>Debt-to-Equity</b>
						</h4>
						<li>
							<p>
								For each{' '}
								{debtToEquityRatio.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}{' '}
								of retained profit you could borrow
							</p>
							<p style={{ display: 'flex', alignItems: 'end' }}>
								{borrowMoney.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</p>
						</li>
					</ul>
					<ul className={props.darkerList}>
						<h4 className={styles.tableHeading}>
							<b>Bank Lending Capacity</b>
						</h4>
						<li>
							<p>Banks would lend from 2.0 x EBITDA</p>
							<p>
								{' '}
								{(banksLendFromEbitda * 2).toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</p>
						</li>
						<li>
							<p>Banks would lend to maximum 2.5 x EBITDA</p>
							<p>
								{' '}
								{(banksLendFromEbitda * 2.5).toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</p>
						</li>
					</ul>
				</div>
				<div className={props.singleSplitColumn}>
					<ul className={props.darkerList}>
						<h4 className={styles.tableHeading}>
							<b>Your cash flow on growth is</b>
						</h4>
						<li>
							<p>Your cash flow on growth is</p>
							<p>
								{cashFlowOnGrowth.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits: 2,
									maximumFractionDigits: 2
								})}
							</p>
						</li>
						<li>
							<small>
								{cashFlowOnGrowth > 0
									? 'You can grow without burning cash'
									: 'Your growth will burn cash'}
							</small>
						</li>
						<li className={`${styles.sub} ${styles.left}`}>
							<small>
								{cashFlowOnGrowth >= 0 && (
									<span className={styles.funding}>
										No funding required — growth is self-sustaining.
									</span>
								)}
								{cashFlowOnGrowth < 0 && (
									<span className={`${styles.funding} ${styles.red}`}>
										Funding required within {fundingReqiredMonths} months at this growth rate.
									</span>
								)}
							</small>
						</li>
					</ul>
					<ul className={props.darkerList}>
						<h4 className={styles.tableHeading}>
							<b>Recommended growth strategy</b>
						</h4>
						<li>
							{/* <small className={`${cashFlowOnGrowth > 0 ? '' : styles.zigZag}`}> */}
							<small>
								{/* {+borrowMoney > 0 ? 'Linear growth' : 'Grow then pause, then grow again'} */}
								{cashFlowOnGrowth > 0 ? 'Linear growth' : 'Zig-zag growth'}
							</small>
						</li>
						{cashFlowOnGrowth > 0 && (
							<li className={styles.sub}>
								<div className={styles.snippet}>
									<h5 style={{ textTransform: 'none' }}>Funding guidance</h5>
									<p>
										<b>Internal:</b> Retained profits.
									</p>
								</div>
							</li>
						)}
						{cashFlowOnGrowth <= 0 && (
							<li className={styles.sub}>
								<div className={`${styles.snippet} ${styles.red}`}>
									<h5 style={{ textTransform: 'none' }}>Financing mix choices at a glance</h5>
									<p>
										<b>Margin-led growth:</b> Focus on increasing high-margin products first (and
										decreasing working capital requirements also).
									</p>
									<p>
										<b>External debt:</b> Bank lending capacity from{' '}
										<b>
											{(banksLendFromEbitda * 2).toLocaleString('en-GB', {
												style: 'currency',
												currency: currencyLabel,
												minimumFractionDigits: 2,
												maximumFractionDigits: 2
											})}
										</b>{' '}
										to{' '}
										<b>
											{(banksLendFromEbitda * 2.5).toLocaleString('en-GB', {
												style: 'currency',
												currency: currencyLabel,
												minimumFractionDigits: 2,
												maximumFractionDigits: 2
											})}
										</b>
									</p>
									<p>
										<b>Equity:</b> Dilution required to cover the gap. Use only when the gap is high
										enough.
									</p>
								</div>
							</li>
						)}
					</ul>
				</div>
			</div>
		</div>
	);
};
export default MoneyForGrowthList;
