/* eslint-disable react/destructuring-assignment */
/* eslint-disable jsx-a11y/label-has-for */
/* eslint-disable jsx-a11y/label-has-associated-control */
import { useContext, useEffect, useState } from 'react';
import CashFlowTitle from '../../../../Components/Layout/Side/Components/CashFlowTitle';
import useCurrencyLabel from '../../../../hooks/useCurrencyLabel';
import type { CashFlowPerspectiveContextModel } from '../../../../Store/CashFlowAnalysis/CashFlowPerspective/CashFlowPerspective-context';
import { CashFlowPerspectiveContext } from '../../../../Store/CashFlowAnalysis/CashFlowPerspective/CashFlowPerspective-context';
import type { FundingMetersModel } from '../../../../Store/CashFlowAnalysis/FundingMeters/FundingMeters-context';
import { FundingMeters } from '../../../../Store/CashFlowAnalysis/FundingMeters/FundingMeters-context';
import styles from './FundingMetersTable.module.scss';
import ToolsTitleNavigation from '../../../ToolsNavigation/ToolsTitleNavigation/ToolsTitleNavigation';
import ToolsIntroAccordion from '../../../ToolsNavigation/ToolsIntroAccordion/ToolsIntroAccordion';
import environment from '../../../../Environments/environment';
import ToolsBottomNavigation from '../../../ToolsNavigation/ToolsBottomNavigation/ToolsBottomNavigation';
import ToolsWhatIsNext from '../../../ToolsNavigation/ToolsWhatIsNext/ToolsWhatIsNext';
import CustomWidthTooltip from '../../../../Components/UI/CustomWidthTooltip/CustomWidthTooltip';
import { useSelector } from 'react-redux';
import type { RootState } from '../../../../ReduxState/store';
import type { FinancialsModel } from '../../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import {
	determinePolarityOfChange,
	decreaseIsGoodThing,
	increaseIsGoodThing
} from '../../../../utils/determinePolarityOfChange';
import getThreeLetterMonthName from '../../../../utils/getThreeLetterMonthName';
import currencyToNumber from '../../../../utils/currencyToNumber';

const FundingMeterTable: React.FC<{ bodyMainParagraph?: string; print?: boolean }> = (props: {
	bodyMainParagraph?: string;
	print?: boolean;
}): JSX.Element => {
	const print = props.print;
	const { financialReturns, moneyForCeos, dashboard } = environment.frontendRoutes;
	const { currencyLabel } = useCurrencyLabel();
	const fundingContext: FundingMetersModel = useContext(FundingMeters);
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);
	const { input } = selectedFinancials
		? selectedFinancials[selectedFinancials.length - 1]
		: { input: { 'Cash at Bank': 0, 'Net Profit': 0, Dividends: 0 } };

	const averageMonthlyBurn = +fundingContext.calculatedCashFlowSecond / 12;
	const runwayRounded = () => {
		const runway = Math.abs(
			+input['Cash at Bank'] / (+fundingContext.calculatedCashFlowSecond / 12)
		);
		const decimalPart = runway - Math.floor(runway);

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

		if (decimalPart < 0.5) {
			return Math.floor(runway);
		}
		return runway.toFixed(2);
	};
	const runway = runwayRounded();
	const perspectiveContext: CashFlowPerspectiveContextModel = useContext(
		CashFlowPerspectiveContext
	);
	// const otherCapital = Math.abs(+perspectiveContext.otherCapitalChange);
	const otherCapital = -1 * +perspectiveContext.otherCapitalChange;
	const otherCapitalVariance = otherCapital.toLocaleString('en-GB', {
		style: 'currency',
		currency: currencyLabel,
		minimumFractionDigits: 0,
		maximumFractionDigits: 0
	});
	// const surplusOrShortfall = +fundingContext.surplusSum + +otherCapital;
	const retainedProfit = +input['Net Profit'] - +input.Dividends;
	const surplusOrShortfall =
		retainedProfit + fundingContext.workingCapitalChangeNumber + +otherCapital;
	// const yourFunding =
	// 	+fundingContext.capitalInvested + (+fundingContext.surplusSum + +otherCapital);
	const yourFunding = +fundingContext.capitalInvested + surplusOrShortfall;
	const currency = localStorage.getItem('currency');
	const [tabletScreen, setTabletScreen] = useState(true);

	const accordionContent = `
							<p class="subtitle">What is this for?</p>
							See how profit turns into cash — and whether you’re funding growth from operations or outside capital.

							<p class="subtitle">What will I get?</p>
							<ul>
								<li>
									Net profit → net cash bridge
								</li>
								<li>Working capital impact on cash/li>
								<li>Funding surplus or shortfall</li>
								<li>Debt-to-equity ratio</li>
							</ul>
							<p class="subtitle">How do I start?</p>
							Check net cash flow first → Follow cash movements → Compare profit vs cash → Review funding sources.`;

	useEffect(() => {
		if (document.body.offsetWidth < 1000) {
			setTabletScreen(false);
		}
	}, []);
	return (
		<div className={`${styles.formContainer} ${print ? styles.print : ''}`}>
			{/* <CashFlowTitle
				className={`${props?.bodyMainParagraph || ''} mb-3`}
				title="Your Cash Flow/Funding Cash Flow Perspective"
			/> */}
			{!print && (
				<ToolsTitleNavigation
					stepNumber={5}
					maxSteps={5}
					title="Funding Overview"
					prevAction={{
						title: 'Back to Returns Analysis',
						link: financialReturns
					}}
					introText="Are you funding growth from profit or debt?"
				/>
			)}
			{!print && (
				<ToolsIntroAccordion content={accordionContent} ctaTitle="Review funding position" />
			)}
			<>
				<div className={styles.tableHeaderFour}>
					<label className={styles.labelClass} htmlFor="otherCapital">
						<b>Cash Flow/Funding</b>
					</label>
					<div style={{ textAlign: 'right' }}>
						<b>
							{getThreeLetterMonthName(perspectiveContext.secondFinancialsMonth)}{' '}
							{perspectiveContext.secondFinancialsYear}
						</b>
					</div>
					<div style={{ textAlign: 'right' }}>
						<b>
							{getThreeLetterMonthName(perspectiveContext.thirdFinancialsMonth)}{' '}
							{perspectiveContext.thirdFinancialsYear}
						</b>
					</div>
					<div style={{ textAlign: 'right' }}>
						<b>Change</b>
					</div>
				</div>
				<div className={styles.valueContainer}>
					<label className={styles.labelClass} htmlFor="priceIncrease">
						<CustomWidthTooltip title="Total borrowing net of cash reserves." />
						Net Debt
					</label>

					<div className={styles.netCashFlow}>{fundingContext.netDebtFirst}</div>
					<div className={styles.netCashFlow}>{fundingContext.netDebtSecond}</div>
					{/* <div className={styles.ebit}>{fundingContext.netDebtChange} %</div> */}
					<div
						className={`${styles.ebit} ${decreaseIsGoodThing(
							currencyToNumber(fundingContext.netDebtFirst),
							currencyToNumber(fundingContext.netDebtSecond)
						)}`}
					>
						{determinePolarityOfChange(
							currencyToNumber(fundingContext.netDebtFirst),
							currencyToNumber(fundingContext.netDebtSecond),
							currencyToNumber(fundingContext.netDebtChange)
						)}{' '}
						%
					</div>
				</div>
				<div className={styles.valueContainer}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						<CustomWidthTooltip title="The residual cash position after inflows and outflows for the period." />
						Net Cash Flow
					</label>
					<div className={styles.netCashFlow}>{fundingContext.netCashFlowFirst}</div>
					<div className={styles.netCashFlow}>{fundingContext.netCashFlowSecond}</div>
					{/* <div className={styles.ebit}>{fundingContext.netCashFlowChange} %</div> */}
					<div
						className={`${styles.ebit} ${increaseIsGoodThing(
							+fundingContext.netCashFlowFirst,
							+fundingContext.netCashFlowSecond
						)}`}
					>
						{determinePolarityOfChange(
							+fundingContext.netCashFlowFirst,
							+fundingContext.netCashFlowSecond,
							+fundingContext.netCashFlowChange
						)}{' '}
						%
					</div>
				</div>
				<div className={styles.valueContainer}>
					<label className={styles.labelClass} htmlFor="cogsReduction">
						<CustomWidthTooltip title="The balance of owner vs. borrowed capital." />
						Debt-to-Equity ( Ratio )
					</label>
					<div className={styles.netCashFlow}>{fundingContext.debtToEquityFirst}</div>
					<div className={styles.netCashFlow}>{fundingContext.debtToEquitySecond}</div>
					{/* <div className={styles.ebit}>{fundingContext.debtToEquityChange} %</div> */}
					<div
						className={`${styles.ebit} ${decreaseIsGoodThing(
							+fundingContext.debtToEquityFirst,
							+fundingContext.debtToEquitySecond
						)}`}
					>
						{determinePolarityOfChange(
							+fundingContext.debtToEquityFirst,
							+fundingContext.debtToEquitySecond,
							+fundingContext.debtToEquityChange
						)}{' '}
						%
					</div>
				</div>
				<div className={styles.valueContainer}>
					<label className={styles.labelClass} htmlFor="overheadReduction">
						<CustomWidthTooltip title="Cash generated by operations, distinct from financing or investment flows." />
						Operating Cash Flow
					</label>
					<div className={styles.netCashFlow} />
					<div className={styles.netCashFlow}>
						{currency} {fundingContext.operatingCashFlow}
					</div>
					<div className={styles.ebit} />
				</div>
				<div style={{ fontSize: '0.925rem', marginTop: '10px' }}>
					💡 <b>Banker lens</b>: Positive operating cash flow + conservative leverage = more
					favourable borrowing terms.
				</div>
			</>
			{/* Your funding table */}
			<p style={{ paddingTop: '35px' }} /> {/* separator */}
			<>
				<CashFlowTitle className={props?.bodyMainParagraph || ''} title="Your Funding" />
				<p />
				<div className={styles.tableHeaderFive}>
					<label className={styles.labelClass} htmlFor="otherCapital" />
					<div />
					<div />
					<div />
					<div style={{ textAlign: 'right' }}>
						<b>Cash in/out</b>
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="priceIncrease">
						{/* Net Profit (after tax) */}
						Retained Profit
					</label>
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{/* {currency} {fundingContext.thirdFinancialNetProfitAftrerTax} */}
						{currency}{' '}
						{retainedProfit.toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits: 0,
							maximumFractionDigits: 0
						})}
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						Working Capital Change
					</label>
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{currency} {fundingContext.workingCapitalChange}
					</div>
				</div>
				<div className={`${styles.valueContainerFive} ${styles.rowEmphasis}`}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						Other Capital
					</label>
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{currency} {otherCapitalVariance}
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="volumeIncrease" />
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit}>Surplus/(Shortfall)</label>
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{surplusOrShortfall.toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits: 0,
							maximumFractionDigits: 0
						})}
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					{tabletScreen && <label className={styles.labelClass} htmlFor="volumeIncrease" />}
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit}>Capital invested/withdrawn</label>
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{parseInt(fundingContext.capitalInvested, 10).toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits: 0,
							maximumFractionDigits: 0
						})}
					</div>
				</div>
				<p style={{ paddingTop: '35px' }} /> {/* separator */}
				<div className={`${styles.valueContainerFive} ${styles.rowEmphasisGray}`}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						<b>Your Funding</b>
					</label>
					<div className={styles.ebit} />
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						<b>
							{yourFunding.toLocaleString('en-GB', {
								style: 'currency',
								currency: currencyLabel,
								minimumFractionDigits: 0,
								maximumFractionDigits: 0
							})}
						</b>
					</div>
				</div>
			</>
			{/* Cash Runway table */}
			<p style={{ paddingTop: '35px' }} /> {/* separator */}
			<>
				<CashFlowTitle className={props?.bodyMainParagraph || ''} title="Cash Runway" />
				<p />
				{/* <div className={styles.tableHeaderFive}>
					<label className={styles.labelClass} htmlFor="otherCapital" />
					<div />
					<div />
					<div />
					<div style={{ textAlign: 'right' }}>Cash in/out</div>
				</div> */}
				<div className={`${styles.valueContainerFive} ${styles.borderTop}`}>
					<label className={styles.labelClass} htmlFor="priceIncrease">
						Current Cash Balance
					</label>
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{(+input['Cash at Bank']).toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits: 0,
							maximumFractionDigits: 0
						})}
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						Average Monthly Burn
					</label>
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						{averageMonthlyBurn.toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits: 0,
							maximumFractionDigits: 0
						})}
					</div>
				</div>
				<div className={`${styles.valueContainerFive} ${styles.rowEmphasisGray}`}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						<b>Runway</b>
					</label>
					{tabletScreen && <p className={styles.ebit} />}
					<label className={styles.ebit} />
					<div className={styles.ebit} />
					<div className={styles.ebit} style={{ textAlign: 'right' }}>
						<b>{runway} months</b>
					</div>
				</div>
			</>
			{/* Profit vs Cashflow table */}
			<p style={{ paddingTop: '35px' }} /> {/* separator */}
			<>
				<CashFlowTitle className={props?.bodyMainParagraph || ''} title="Profit vs Cash flow" />
				<p className={`${styles.pcfYear} mb-3`}>Year {fundingContext.thirdFinancialYear}</p>
				<div className={styles.pcfHeader}>
					<label className={styles.labelClass} style={{ textAlign: 'left' }} htmlFor="otherCapital">
						<b>Profit</b>
					</label>
					<div style={{ textAlign: 'center' }}>
						<b>Cash Flow</b>
					</div>
					<div style={{ textAlign: 'right' }}>
						<b>Variance</b>
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="priceIncrease">
						Revenue
					</label>
					<div className={styles.ebit}>
						{currency} {fundingContext.revenueFirst}
					</div>
					<label className={styles.ebit}>Cash from Customers</label>
					<div className={styles.ebit}>
						{currency} {fundingContext.cashFromCustomers}
					</div>
					<div className={styles.ebit}>
						{currency} {fundingContext.revenueVariance}
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						Direct Costs
					</label>
					<div className={styles.ebit}>
						{currency} {fundingContext.directCost}
					</div>
					<label className={styles.ebit}>Cash to Suppliers</label>
					<div className={styles.ebit}>
						{currency} {fundingContext.cashToSupplier}
					</div>
					<div className={styles.ebit}>
						{currency} {fundingContext.cashToSupplierVariance}
					</div>
				</div>
				<div className={`${styles.valueContainerFive} ${styles.rowEmphasisGray}`}>
					<label className={styles.lastLabel} htmlFor="cogsReduction">
						<b>Gross Margin</b>
					</label>
					<div className={styles.ebit}>
						<b>
							{currency} {fundingContext.grossMargin}
						</b>
					</div>
					<label className={styles.lastLabel}>
						<b>Gross Cash Profit</b>
					</label>
					<div className={styles.ebit}>
						<b>
							{currency} {fundingContext.grossProfit}
						</b>
					</div>
					<div className={styles.ebit}>
						<b>
							{currency} {fundingContext.grossProfitVariance}
						</b>
					</div>
				</div>
				<div className={styles.valueContainerFive}>
					<label className={styles.labelClass} htmlFor="overheadReduction">
						Overheard Exc. Deprecation
					</label>
					<div className={styles.ebit}>
						{currency} {fundingContext.overheadsExcluded}
					</div>
					<label className={styles.ebit}>Overheard Exc. Deprecation</label>
					<div className={styles.ebit}>
						{currency} {fundingContext.overheadsExcluded}
					</div>
					<div className={styles.ebit}>
						{currency} {fundingContext.overheadsExcludedVariance}
					</div>
				</div>
				<div className={`${styles.valueContainerFive} ${styles.rowEmphasisGray}`}>
					<label className={styles.lastLabel} htmlFor="overheadReduction">
						<b>Operating Cash Profit</b>
					</label>
					<div className={styles.ebit}>
						<b>
							{currency} {fundingContext.operatingCashProfit}
						</b>
					</div>
					<label className={styles.lastLabel}>
						<b>Operating Cash Flow</b>
					</label>
					<div className={styles.ebit}>
						<b>
							{currency} {fundingContext.operatingCashFlow}
						</b>
					</div>
					<div className={styles.ebit}>
						<b>
							{currency} {fundingContext.operatingCashFlowVariance}
						</b>
					</div>
				</div>
			</>
			{!print && (
				<ToolsBottomNavigation
					stepNumber={5}
					maxSteps={5}
					prevAction={{
						title: 'Back to Returns Analysis',
						link: financialReturns
					}}
					reportGenerated={() => {}}
				/>
			)}
			{!print && (
				<ToolsWhatIsNext
					prevAction={{
						title: 'Tune my strategy',
						content:
							'Now that you know your cash flow drivers, revisit your multiplier levers to tune for better outcomes.',
						link: moneyForCeos
					}}
					nextAction={{
						title: 'Go to Dashboard',
						content:
							'Head to your <i>Dashboard</i> for a clear, visual summary of your profitability, liquidity, and growth metrics – all in one place.',
						link: dashboard
					}}
				/>
			)}
		</div>
	);
};

export default FundingMeterTable;
