import type React from 'react';
import { useContext, useEffect, useState } from 'react';

import type { CashFlowMetricModel } from '../../../../Store/CashFlowAnalysis/CashFlowMetric/CashFlowMetric-context';
import { CashFlowMetricContext } from '../../../../Store/CashFlowAnalysis/CashFlowMetric/CashFlowMetric-context';
import styles from '../../../MoneyForCeos/Components/MoneyForCeosTable.module.scss';
import { useSelector } from 'react-redux';
import type { RootState } from '../../../../ReduxState/store';
import type { CompanyDbModel } from '../../../Companies/Components/CompaniesComponents.helper';
import getCompanyType from '../../../../utils/getCompanyType';
import CustomWidthTooltip from '../../../../Components/UI/CustomWidthTooltip/CustomWidthTooltip';
import getThreeLetterMonthName from '../../../../utils/getThreeLetterMonthName';
import {
	determinePolarityOfChange,
	decreaseIsGoodThing,
	increaseIsGoodThing
} from '../../../../utils/determinePolarityOfChange';

const CashFlowMetricTable: React.FC = (): JSX.Element => {
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const [currencyLabel, setCurrencyLabel] = useState<string>('GBP');

	useEffect(() => {
		if (selectedCompany) {
			setCurrencyLabel(
				`${
					typeof selectedCompany?.currency_symbol === 'string'
						? 'GBP'
						: selectedCompany?.currency_symbol.value
				}`
			);
		}
	}, [selectedCompany]);

	const minimumFractionDigits = 0;
	const maximumFractionDigits = 0;
	const companyType = getCompanyType(selectedCompany);
	const cashFlowContext: CashFlowMetricModel = useContext(CashFlowMetricContext);
	return (
		<>
			<div className={styles.formContainer}>
				<div className={styles.tableHeadWorkingMetric}>
					<p>
						<b>Working Capital</b>
					</p>
					<p>
						<b>
							{getThreeLetterMonthName(cashFlowContext.secondMonth)} {cashFlowContext.secondYear}
						</b>
					</p>
					<p>
						<b>
							{getThreeLetterMonthName(cashFlowContext.thirdMonth)} {cashFlowContext.thirdYear}
						</b>
					</p>
					<p>
						<b>Change</b>
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="priceIncrease">
						<CustomWidthTooltip title="Average time to collect customer payments; a key lever for liquidity." />
						<b>Debtor Days</b>
					</label>

					<p className={styles.netCashFlow}>{cashFlowContext.debtorsDay}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.debtorsDaySecond}</p>
					<p
						className={`styles.ebit ${decreaseIsGoodThing(
							+cashFlowContext.debtorsDay,
							+cashFlowContext.debtorsDaySecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.debtorsDay,
							+cashFlowContext.debtorsDaySecond,
							+cashFlowContext.debtorsDayChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						{companyType === 'All Other' && (
							<CustomWidthTooltip title="Average time cash is tied in inventory before it converts into sales." />
						)}
						{companyType !== 'All Other' && (
							<CustomWidthTooltip title="Work-in-Progress days is the average time projects remain incomplete; higher = cash tied up longer." />
						)}
						<b>{companyType === 'All Other' ? 'Stock Days' : 'WIP Days'}</b>
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.wipDaysFirst}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.wipDaysSecond}</p>
					<p
						className={`styles.ebit ${decreaseIsGoodThing(
							+cashFlowContext.wipDaysFirst,
							+cashFlowContext.wipDaysSecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.wipDaysFirst,
							+cashFlowContext.wipDaysSecond,
							+cashFlowContext.wipDaysChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="volumeIncrease">
						<CustomWidthTooltip title="Average days you take to pay suppliers; longer retains cash longer." />
						<b>Creditor Days</b>
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.creditorsDay}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.creditorsDaySecond}</p>
					<p
						className={`styles.ebit ${increaseIsGoodThing(
							+cashFlowContext.creditorsDay,
							+cashFlowContext.creditorsDaySecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.creditorsDay,
							+cashFlowContext.creditorsDaySecond,
							+cashFlowContext.creditorsDayChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="cogsReduction">
						<CustomWidthTooltip title="Time between receiving payment and delivery; upfront cash boosts runway." />
						Deferred Revenue Days
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.deferredRevenueDays}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.deferredRevenueDaysSecond}</p>
					<p
						className={`styles.ebit ${increaseIsGoodThing(
							+cashFlowContext.deferredRevenueDays,
							+cashFlowContext.deferredRevenueDaysSecond
						)}`}
					>
						{cashFlowContext.deferredRevenueDaysChange !== 'NaN'
							? determinePolarityOfChange(
									+cashFlowContext.deferredRevenueDays,
									+cashFlowContext.deferredRevenueDaysSecond,
									+cashFlowContext.deferredRevenueDaysChange
							  )
							: '0.00'}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="cogsReduction">
						<CustomWidthTooltip title="The full cycle time to turn investment in operations back into cash; lower means faster cash conversion." />
						<b>Working Capital Days</b>
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.workingCapitalDays}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.workingCapitalDaysSecond}</p>
					<p
						className={`styles.ebit ${decreaseIsGoodThing(
							+cashFlowContext.workingCapitalDays,
							+cashFlowContext.workingCapitalDaysSecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.workingCapitalDays,
							+cashFlowContext.workingCapitalDaysSecond,
							+cashFlowContext.workingCapitalDaysChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="overheadReduction">
						<CustomWidthTooltip title="The net cash required to sustain trading and growth." />
						<b>Working Capital</b>
					</label>
					<p className={styles.netCashFlow}>
						{(+cashFlowContext.workingCapital).toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits,
							maximumFractionDigits
						})}
					</p>
					<p className={styles.netCashFlow}>
						{(+cashFlowContext.workingCapitalSecond).toLocaleString('en-GB', {
							style: 'currency',
							currency: currencyLabel,
							minimumFractionDigits,
							maximumFractionDigits
						})}
					</p>
					<p
						className={`styles.ebit ${decreaseIsGoodThing(
							+cashFlowContext.workingCapital,
							+cashFlowContext.workingCapitalSecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.workingCapital,
							+cashFlowContext.workingCapitalSecond,
							+cashFlowContext.workingCapitalChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="overheadReduction">
						<CustomWidthTooltip title="Working capital scaled to revenue size." />
						Working Capital (% of Revenue)
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.workingCapitalPercent} %</p>
					<p className={styles.netCashFlow}>{cashFlowContext.workingCapitalPercentSecond} %</p>
					<p
						className={`styles.ebit ${decreaseIsGoodThing(
							+cashFlowContext.workingCapitalPercent,
							+cashFlowContext.workingCapitalPercentSecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.workingCapitalPercent,
							+cashFlowContext.workingCapitalPercentSecond,
							+cashFlowContext.workingCapitalPercentChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="debtorsDayReductions">
						<CustomWidthTooltip title="How much cash your business actually keeps from the next £1 of sales — after covering direct costs and working capital needs." />
						<b>Marginal Cash Flow</b>
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.marginalCashFlow}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.marginalCashFlowSecond}</p>
					<p
						className={`styles.ebit ${increaseIsGoodThing(
							+cashFlowContext.marginalCashFlow,
							+cashFlowContext.marginalCashFlowSecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.marginalCashFlow,
							+cashFlowContext.marginalCashFlowSecond,
							+cashFlowContext.marginalCashFlowChange
						)}{' '}
						%
					</p>
				</div>
				<div className={styles.inputContainerCashFlowMetric}>
					<label className={styles.labelClass} htmlFor="reductionInWipDays">
						<CustomWidthTooltip title="Short-term solvency measure: assets available to cover near-term liabilities." />
						Current Ratio
					</label>
					<p className={styles.netCashFlow}>{cashFlowContext.currentRatio}</p>
					<p className={styles.netCashFlow}>{cashFlowContext.currentRatioSecond}</p>
					<p
						className={`styles.ebit ${increaseIsGoodThing(
							+cashFlowContext.currentRatio,
							+cashFlowContext.currentRatioSecond
						)}`}
					>
						{determinePolarityOfChange(
							+cashFlowContext.currentRatio,
							+cashFlowContext.currentRatioSecond,
							+cashFlowContext.currentRatioChange
						)}{' '}
						%
					</p>
				</div>
			</div>
			<div className={styles.formContainer}>
				<div className={styles.tableHead}>
					<p>
						<b>Cash Conversion from Sales</b>
					</p>
					<p>
						<b>
							{getThreeLetterMonthName(cashFlowContext.secondMonth)} {cashFlowContext.secondYear}
						</b>
					</p>
					<p>
						<b>
							{getThreeLetterMonthName(cashFlowContext.thirdMonth)} {cashFlowContext.thirdYear}
						</b>
					</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="reductionInWipDays">
						<CustomWidthTooltip title="Profit after direct costs from the next unit of sales." />
						Gross Margin for Next 1 of Sales
					</label>
					<p />
					<p>{cashFlowContext.grossMarginForNextPoundSale} %</p>
					<p>{cashFlowContext.grossMarginForNextPoundSaleSecond} %</p>
				</div>
				<div className={styles.inputContainer}>
					<label className={styles.labelClass} htmlFor="priceIncrease">
						<CustomWidthTooltip title="Difference between cash available and cash needed to support your next dollar of sales." />
						Your Gap
					</label>

					<p className={styles.ebit} />
					<p className={styles.netCashFlow}>{+cashFlowContext.yourGap * -1} %</p>
					<p className={styles.netCashFlow}>{+cashFlowContext.yourGapSecond * -1} %</p>
				</div>
				<div style={{ fontSize: '0.925rem', marginTop: '10px' }}>
					💡 <b>Boardroom lens</b>: Reducing debtor days by 10 can unlock the same liquidity as
					raising new capital.
				</div>
			</div>
		</>
	);
};

export default CashFlowMetricTable;
