/* eslint-disable react/jsx-no-bind */
/* eslint-disable @typescript-eslint/no-unused-vars */
import type React from 'react';
import { useContext, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';

import InsightsHeader from '../../../Components/Layout/Header/InsightsHeader';
import CashFlowDescriptionText from '../../../Components/Layout/Side/Components/CashFlowDescriptionText';
import ButtonClickErrorMessage from '../../../Components/UI/ErrorMessages/ButtonClickErrorMessage';
import environment from '../../../Environments/environment';
import type { RootState } from '../../../ReduxState/store';
import CashFlowAnalysisContextProvider from '../../../Store/CashFlowAnalysis/CashFlowSummary/CahsFlowAnalysisSummary-context';
import FinancialsContextProvider, {
	FinancialsContext
} from '../../../Store/Financials/financials-context';

import type { GlobalStateModel } from '../../../Store/global/GlobalState-context';
import { GlobalStateContext } from '../../../Store/global/GlobalState-context';
import type { FinancialsInterface, FinancialsModel } from '../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import MoneyForCeosTable from '../../MoneyForCeos/Components/MoneyForCeosTable';
import toolsWording from '../../Tools/tools.wording';
import styles from './CashFlowSummary.module.scss';
import CashFlowCards from './Components/CashFlowCards';
import CashFlowSubTitle from './Components/CashFlowSubTitle';
import Wording from './Components/CashFlowTitle.helper';
import SideCards from './Components/SideCards';
import ToolsTitleNavigation from '../../ToolsNavigation/ToolsTitleNavigation/ToolsTitleNavigation';
import ToolsIntroAccordion from '../../ToolsNavigation/ToolsIntroAccordion/ToolsIntroAccordion';
import ToolsBottomNavigation from '../../ToolsNavigation/ToolsBottomNavigation/ToolsBottomNavigation';
import { FundingMeters, type FundingMetersModel } from '../../../Store/CashFlowAnalysis/FundingMeters/FundingMeters-context';
import roundToTwoDecimals from '../../../utils/roundToMaxTwoDecimals';

const CashFlowSummary: React.FC<{ print?: boolean }> = ({
	print
}: {
	print?: boolean;
}): JSX.Element => {
	const { moneyForGrowth, financials, cashFlowPerspective } = environment.frontendRoutes;
	const [switchPage, setSwitchPage] = useState<boolean>(
		JSON.parse(localStorage.getItem('switchToPage') as string)
	);
	const fundingContext: FundingMetersModel = useContext(FundingMeters);
	const numberOfSelectedFinancials = 3;
	const [errorMessage, setErrorMessage] = useState<boolean>(false);
	const [errorMessagePopup, setErrorMessagePopup] = useState<boolean>(false);
	const globalContext: GlobalStateModel = useContext<GlobalStateModel>(GlobalStateContext);
	const navigate = useNavigate();

	const {
		description,
		title,
		toolInfo,
		listTextOne,
		listTextSecond,
		listTextThird,
		listTextFourth
	} = toolsWording.cashFlowAnalysis.props;

	const [fundingReqiredMonths, setFundingReqiredMonths] = useState<string | number>('0');
	const [showPage, setShowPage] = useState<boolean>(false);
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);
	useEffect(() => {
		window.scrollTo(0, 0);
		if (selectedFinancials) {
			if (selectedFinancials?.length < 1) {
				navigate(financials);
			} else {
				setShowPage(true);
			}
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);
	/** NEW end */

	const runwayRounded = (input: FinancialsInterface) => {
		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);
	};

	useEffect(() => {
		console.log('selected financials in cashflowsummary', selectedFinancials);
		if (selectedFinancials) {
			const { input } = selectedFinancials[selectedFinancials.length - 1];
			console.log('+fundingContext.calculatedCashFlowSecond', +fundingContext.calculatedCashFlowSecond)
			const fundingMonths = runwayRounded(input);
			console.log('funding months', +input['Cash at Bank'], +fundingContext.calculatedCashFlowSecond, 12, +input['Cash at Bank'] / +fundingContext.calculatedCashFlowSecond / 12)
			setFundingReqiredMonths(fundingMonths);

			if (selectedFinancials?.length < 3) {
				navigate(`${financials}?tool=cashFlowAnalysis`);
			} else {
				setShowPage(true);
			}
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectedFinancials, fundingContext]);

	const accordionContent = `
							<p class="subtitle">What is this for?</p>
							Gain insight into the drivers of cash flow — and see how operations and timing
							impact liquidity and financial returns.
							<p class="subtitle">What will I get?</p>
							<ul>
								<li>
									A connected view of profitability, working capital, returns, and funding
									position — from a cash perspective.
								</li>
								<li>See how operations, timing, and performance shape your cash health.</li>
							</ul>
							<p class="subtitle">Key Reports & Tools</p>
							<ul>
								<li>
									<b>Profitability</b> – Track margins, cost growth, and productivity.
								</li>
								<li>
									<b>Working Capital</b> – Understand your cash cycle and capital tied in
									operations.
								</li>
								<li>
									<b>Returns</b> – Measure ROIC, ROE, and asset efficiency.
								</li>
								<li>
									<b>Funding</b> – See your net cash flow, debt levels, and capital structure.
								</li>
							</ul>
							<p class="subtitle">How do I start?</p>
							Select your financials — we’ll turn them into easy-to-read dashboards with no
							spreadsheets required.
							<p class="subtitle">💡 Strategy Tip</p>
							<i>Follow the cash, not just the profit</i>. A business can be profitable on
							paper yet still run out of cash. Use this analysis to pinpoint exactly where
							cash is generated, delayed, or lost — and act before liquidity issues slow your
							growth.`;

	return (
		<div className={styles.container}>
			<CashFlowAnalysisContextProvider>
				<div className={styles.body}>
					{!print && <InsightsHeader numberOfButtons={3} title="Cash Flow Analytics" />}
					{showPage && (
						<div className={styles.body__main}>
							<ToolsTitleNavigation
								title="Cash Flow Analytics Summary"
								stepNumber={1}
								maxSteps={5}
								nextAction={{ link: environment.frontendRoutes.cashFlowPerspective, title: 'Next' }}
								introText="How healthy is your cash engine?"
							/>
							{!print && (
								<ToolsIntroAccordion
									content={accordionContent}
									ctaTitle="Start my cash flow analysis"
								/>
							)}
							<CashFlowDescriptionText classNameParagraph={styles.titleDescription} subTitle="" />
							<div
								className={`${styles.body__main__cards} ${
									print ? styles.print_body__main__cards : ''
								}`}
							>
								<CashFlowCards
									card={styles.cardsContainer__card}
									container={styles.cardsContainer}
								/>
								<SideCards
									card={styles.sideCardsContainer__card}
									container={styles.sideCardsContainer}
									title={styles.sideCardsContainer__card__title}
								/>
							</div>
							<div style={{ marginTop: '20px' }}>
								<b>Cash Runway:</b> Your current cash balance gives you {fundingReqiredMonths}{' '}
								months runway (see{' '}
								<Link to={environment.frontendRoutes.cashFundingMeters} className="link">
									Funding section
								</Link>{' '}
								for details).
							</div>
							<CashFlowSubTitle
								container={`${styles.cashFlowSubTitleContainer} ${
									print ? styles.cashFlowSubTitleContainerPrint : ''
								}`}
								text={Wording.summaryText}
								title={Wording.summaryTitle}
							/>
							<FinancialsContextProvider>
								<MoneyForCeosTable />
							</FinancialsContextProvider>
							{/* {!print && (
								<CashFlowFooter
									backTo={financials}
									buttonClassName={styles.footerContainer__button}
									buttonHelpText=""
									buttonText="View profitability metrics"
									classNameBtnHelperText={styles.footerContainer__buttonTextHelper}
									container={styles.footerContainer}
									linkText="Back to financials"
									linkTo={cashFlowPerspective}
									svgClassName={styles.footerContainer__svg}
								/>
							)} */}

							{!print && (
								<ToolsBottomNavigation
									stepNumber={1}
									maxSteps={5}
									prevAction={{
										title: 'Back to Money for Growth',
										link: moneyForGrowth
									}}
									nextAction={{
										title: 'Next: Profitability Trends',
										link: cashFlowPerspective
									}}
								/>
							)}
						</div>
					)}
					{/* {!showPage && (
						<FinancialsContextProvider>
							<SelectFinancialsPage
								buttonId=""
								buttonTitle="View profitability metrics"
								companies={globalContext.companies}
								description={description}
								isListOn
								linkHandler={switchHandler}
								listTextFourth={listTextFourth}
								listTextOne={listTextOne}
								listTextSecond={listTextSecond}
								listTextThird={listTextThird}
								numberOfFinancials={numberOfSelectedFinancials}
								title={title}
								toolInfo={toolInfo}
							/>
						</FinancialsContextProvider>
					)} */}
					{errorMessage && (
						<ButtonClickErrorMessage
							allCompanies={globalContext.companies}
							closeHandler={() => setErrorMessage(false)}
							financialsNumber={3}
						/>
					)}
					{errorMessagePopup && (
						<div className={styles.errorMessagePopup}>
							<h4>You need to select {numberOfSelectedFinancials} financials to continue</h4>
						</div>
					)}
				</div>
			</CashFlowAnalysisContextProvider>
		</div>
	);
};

export default CashFlowSummary;
