/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/destructuring-assignment */
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import Accordion from '@mui/material/Accordion';
import AccordionDetails from '@mui/material/AccordionDetails';
import AccordionSummary from '@mui/material/AccordionSummary';
import Typography from '@mui/material/Typography';
import * as React from 'react';
import { useContext, useDeferredValue, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

import type { RootState } from '../../../ReduxState/store';
import type { FinancialsContextModel } from '../../../Store/Financials/financials-context';
import { FinancialsContext } from '../../../Store/Financials/financials-context';
import type { CompanyDbModel } from '../../Companies/Components/CompaniesComponents.helper';
import type { FinancialsModel } from '../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import { formDefaultValues } from '../../Financials/Components/FinancialsForm/FinancialsForm.helper';
import getCompanyType from '../../../utils/getCompanyType';
import calculateImpactOfMultiplierAdjustmentOnValuation, {
	type MatchKeys,
	matchValueToTitle
} from './MoneyForCeosBusinessAccordion.helper';
import CustomWidthQuickWinTooltip from '../../../Components/UI/CustomWidthQuickWinTooltip/CustomWidthQuickWinTooltip';
import styles from './MoneyForCeosBusinessAccordion.module.scss'

interface AccordionInterface {
	className: string;
	accordionDetails: string;
	listOfItems: string;
	nonSelected: string;
	selected: string;
	print: string;
	forcePrintStyle: string;
}

const MoneyForCeosBusinessAccordion: React.FC<AccordionInterface> = (
	props: AccordionInterface
): JSX.Element => {
	console.log('print', props.print);
	const minimumFractionDigits = 0;
	const maximumFractionDigits = 0;
	const print = props.print;
	const [expanded, setExpanded] = React.useState<string | false>('panel3');
	const [isSelected, setIsSelected] = React.useState<string>(props.nonSelected);
	const [isSelected2, setIsSelected2] = React.useState<string>(props.nonSelected);
	const [isSelected3, setIsSelected3] = React.useState<string>(props.selected);
	const financialContext: FinancialsContextModel = useContext(FinancialsContext);
	const selectedFinancials = useSelector(
		(state: RootState): FinancialsModel[] | null => state.financials.selectedFinancials
	);
	const selectedCompany = useSelector(
		(state: RootState): CompanyDbModel | null => state.companies.selectedCompany
	);
	const currencyLabel = `${
		!selectedCompany || typeof selectedCompany?.currency_symbol === 'string'
			? 'GBP'
			: selectedCompany?.currency_symbol.value
	}`;
	const companyType = getCompanyType(selectedCompany);

	const handleChange = (panel: string) => (event: React.SyntheticEvent, newExpanded: boolean) => {
		setExpanded(newExpanded ? panel : false);
		if (panel === 'panel1') {
			setIsSelected(props.selected);
			setIsSelected2(props.nonSelected);
			setIsSelected3(props.nonSelected);
		} else if (panel === 'panel2') {
			setIsSelected2(props.selected);
			setIsSelected3(props.nonSelected);
			setIsSelected(props.nonSelected);
		} else if (panel === 'panel3') {
			setIsSelected3(props.selected);
			setIsSelected2(props.nonSelected);
			setIsSelected(props.nonSelected);
		}
	};

	const { weightedAverageEBITDA, lessTotalDebt, equityValuation, actualEquity, ebitdaValue, enhancedBusinessValueIndicator } =
		financialContext;

	const [firstFinancial, setFirstFinancial] = useState<FinancialsModel>({
		input: formDefaultValues,
		company_id: '',
		selected: false,
		financials_id: '',
		cognito_username: ''
	});

	const [lastFinancial, setLastFinancial] = useState<FinancialsModel>({
		input: formDefaultValues,
		company_id: '',
		selected: false,
		financials_id: '',
		cognito_username: ''
	});
	const priceIncreaseIndex = useDeferredValue(
		JSON.parse(localStorage.getItem('priceIncreaseIndex') as string)
	);
	const volumeIncreaseIndex = useDeferredValue(
		JSON.parse(localStorage.getItem('volumeIncreaseIndex') as string)
	);
	const cogsIndex = useDeferredValue(JSON.parse(localStorage.getItem('cogsIndex') as string));
	const overheadReductionIndex = useDeferredValue(
		JSON.parse(localStorage.getItem('overheadReductionIndex') as string)
	);
	const debtorsDayReduction = useDeferredValue(
		JSON.parse(localStorage.getItem('debtorsDayReduction') as string)
	);
	const reductionWipDays = useDeferredValue(
		JSON.parse(localStorage.getItem('reductionWipDays') as string)
	);
	console.log('reduction in wip days', reductionWipDays)
	const increaseInCreditorsDays = useDeferredValue(
		JSON.parse(localStorage.getItem('increaseInCreditorsDays') as string)
	);
	const increaseInDeferredRevenueDays = useDeferredValue(
		JSON.parse(localStorage.getItem('increaseInDeferredRevenueDays') as string)
	);

	// TODO: to be finished only if necessary
	const popupMessage = () => {
		const totalImpact = Math.round(financialContext.netCashFlowSum / 1000);
		const deptorDaysReduction = (+lastFinancial.input.Revenue / 365) * debtorsDayReduction;
		const reductionInStockDays = (+lastFinancial.input.Revenue / 365) * reductionWipDays;
		const increaseInCreditorsDaysC = (+lastFinancial.input.COGS / 365) * increaseInCreditorsDays;

		const message = `Key metric improvements:
		<p>“+${currencyLabel}${totalImpact}K in cash flow unlocked”</p>
		<p>“Cash unlocked from working capital reduction (sobirame: Debtor Days Reduction + Reduction in Stock Days + Increase in Creditor Days + Increase in Deferrred Revenue Days)”</p>
		<p>“Valuation increased by £1.2M (vrednosta na: Impact of Multiplier Simulator on Valuation)</p>`;
	};

	// use selectedFinancials approach
	useEffect(() => {
		if (JSON.parse(localStorage.getItem('third-financial') as string)) {
			setLastFinancial(JSON.parse(localStorage.getItem('third-financial') as string));
			setFirstFinancial(JSON.parse(localStorage.getItem('second-financial') as string));
		} else if (
			JSON.parse(localStorage.getItem('second-financial') as string) &&
			!JSON.parse(localStorage.getItem('third-financial') as string)
		) {
			setLastFinancial(JSON.parse(localStorage.getItem('second-financial') as string));
			setFirstFinancial(JSON.parse(localStorage.getItem('first-financial') as string));
		}

		// use selectedFinancials
		if (selectedFinancials && selectedFinancials?.length >= 2) {
			setLastFinancial(selectedFinancials[selectedFinancials.length - 1]);
			setFirstFinancial(selectedFinancials[selectedFinancials.length - 2]);
		}

		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectedFinancials]);

	const equityValuationValue = weightedAverageEBITDA * +ebitdaValue - lessTotalDebt;
	const resultOfCalculateImpact = calculateImpactOfMultiplierAdjustmentOnValuation({
		companyType,
		revenue: lastFinancial.input.Revenue,
		grossProfit: +lastFinancial.input['Gross Profit'],
		cogs: +lastFinancial.input.COGS,
		ebit: +lastFinancial.input.EBIT,
		deferredRevenue: +lastFinancial.input['Deferred Revenue'],
		priceIncreaseIndex,
		volumeIncreaseIndex,
		cogsIndex,
		overheadReductionIndex,
		debtorsDayReduction,
		reductionWipDays,
		increaseInDeferredRevenueDays,
		increaseInCreditorsDays,
		ebitdaValue
	});

	const {
		priceIncreaseValue,
		volumeIncreaseValue,
		cogsReductionValue,
		overheadReductionValue,
		profitImpactOnValuationValue,
		debtorsDaysReductionValue,
		reductionInStockDaysValue,
		increaseInDeferredRevenueDaysValue,
		increaseInCreditorsDaysValue,
		cashImpactOnValuationValue,
		totalImpactOnValuationValue,
		topImpacts
	} = resultOfCalculateImpact;

	const renderTopImpact = () => 
		<ul className={styles.topImpacts}>
			{topImpacts.map((impactValue, index) => (
				<li key={index}>
					<small>{matchValueToTitle(impactValue as MatchKeys)} Impact %</small>
					<small>
						+{(
							((resultOfCalculateImpact as any)[impactValue]  /
							equityValuationValue)* 100
						).toFixed(2)}% of valuation
					</small>
				</li>
			))}
		</ul>

	return (
		<div className={props.className}>
			<Accordion expanded={!!print || expanded === 'panel1'} onChange={handleChange('panel1')}>
				<AccordionSummary
					aria-controls="panel1a-content"
					className={isSelected}
					expandIcon={<ExpandMoreIcon />}
					id="panel1a-header"
				>
					<Typography><b>Current Business Value Indicator</b></Typography>
				</AccordionSummary>
				<AccordionDetails
					className={`${props.accordionDetails} ${print ? props.print : ''} ${
						props.forcePrintStyle ? props.forcePrintStyle : ''
					}`}
				>
					{/* <Typography className={props.listOfItems}> */}
					<ul className={styles.ulAsTable}>
						<li>
							<small>Weighted Average EBITDA (Basic Valuation)</small>
							<small>
								{(weightedAverageEBITDA * +ebitdaValue).toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>Less total debt</small>
							<small>{lessTotalDebt.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')}</small>
						</li>
						<li>
							<small>Equity Valuation</small>
							<small>
								{equityValuationValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>Actual Equity</small>
							<small>{actualEquity.toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')}</small>
						</li>
					</ul>
					{/* </Typography> */}
				</AccordionDetails>
			</Accordion>
			<Accordion expanded={!!print || expanded === 'panel2'} onChange={handleChange('panel2')}>
				<AccordionSummary
					aria-controls="panel2a-content"
					className={isSelected2}
					expandIcon={<ExpandMoreIcon />}
					id="panel2a-header"
				>
					<Typography><b>Impact of Multiplier Adjustment on Valuation</b></Typography>
				</AccordionSummary>
				<AccordionDetails
					className={`${props.accordionDetails} ${print ? props.print : ''} ${
						props.forcePrintStyle ? props.forcePrintStyle : ''
					}`}
				>
					<ul className={styles.ulAsTable}>
						<li>
							<small>
								Price Increase
								{topImpacts.includes('priceIncreaseValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{priceIncreaseValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>
								Volume Increase
								{topImpacts.includes('volumeIncreaseValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{volumeIncreaseValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>
								CoGS Reduction
								{topImpacts.includes('cogsReductionValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{cogsReductionValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>
								Overhead Reduction
								{topImpacts.includes('overheadReductionValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{overheadReductionValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li className={styles.rowEmphasis}>
							<small>
								<b>Profit Impact on Valuation</b>
								{topImpacts.includes('profitImpactOnValuationValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								<b>
									{profitImpactOnValuationValue.toLocaleString('en-GB', {
										style: 'currency',
										currency: currencyLabel,
										minimumFractionDigits,
										maximumFractionDigits
									})}
								</b>
							</small>
						</li>
						<li>
							<small>
								Debtors Days Reduction
								{topImpacts.includes('deptorDaysReductionValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{debtorsDaysReductionValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>
								{companyType === 'All Other' ? 'Reduction in Stock Days' : 'Reduction in WIP Days'}
								{topImpacts.includes('reductionInStockDaysValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{reductionInStockDaysValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>
								Increase in Deferred Revenue Days
								{topImpacts.includes('increaseInDeferredRevenueDays') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{increaseInDeferredRevenueDaysValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li>
							<small>
								Increase in Creditors Days
								{topImpacts.includes('increaseInCreditorsDaysValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								{increaseInCreditorsDaysValue.toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						<li className={styles.rowEmphasis}>
							<small>
								<b>Cash Impact on Valuation</b>
								{topImpacts.includes('cashImpactOnValuationValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								<b>
									{cashImpactOnValuationValue.toLocaleString('en-GB', {
										style: 'currency',
										currency: currencyLabel,
										minimumFractionDigits,
										maximumFractionDigits
									})}
								</b>
							</small>
						</li>
						<li className={styles.rowEmphasis}>
							<small>
								<b>Total Impact on Valuation</b>
								{topImpacts.includes('totalImpactOnValuationValue') && (
									<CustomWidthQuickWinTooltip title="This lever delivers the fastest growth of your sale value. Prioritise this for long-term results." />
								)}
							</small>
							<small>
								<b>
									{totalImpactOnValuationValue.toLocaleString('en-GB', {
										style: 'currency',
										currency: currencyLabel,
										minimumFractionDigits,
										maximumFractionDigits
									})}
								</b>
							</small>
						</li>
					</ul>
				</AccordionDetails>
			</Accordion>
			<Accordion expanded={!!print || expanded === 'panel3'} onChange={handleChange('panel3')}>
				<AccordionSummary
					aria-controls="panel3a-content"
					className={isSelected3}
					expandIcon={<ExpandMoreIcon />}
					id="panel3a-header"
				>
					<Typography><b>Enhanced Business Value Indicator</b></Typography>
				</AccordionSummary>
				<AccordionDetails
					className={`${props.accordionDetails} ${print ? props.print : ''} ${
						props.forcePrintStyle ? props.forcePrintStyle : ''
					}`}
				>
					{/* <Typography className={props.listOfItems}> */}
					<ul className={styles.ulAsTable}>
						<li>
							<small>Equity Valuation</small>
							<small>
								{(weightedAverageEBITDA * +ebitdaValue - lessTotalDebt).toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}
							</small>
						</li>
						{renderTopImpact()}
						<li className={styles.rowEmphasis}>
							<small><b>Impact of Multiplier Simulator on Valuation</b></small>
							<small>
								<b>
									{/* {(
										+(
											+((+lastFinancial.input.Revenue * +priceIncreaseIndex) / 100) +
											+((+lastFinancial.input['Gross Profit'] * +volumeIncreaseIndex) / 100) +
											+((+lastFinancial.input.COGS * +cogsIndex) / 100) +
											+(
												((+lastFinancial.input['Gross Profit'] - +lastFinancial.input.EBIT) *
													+overheadReductionIndex) /
												100
											)
										) *
											ebitdaValue +
										+(
											+((+lastFinancial.input.Revenue / 365) * debtorsDayReduction) +
											+((+lastFinancial.input.Revenue / 365) * reductionWipDays) +
											+((+lastFinancial.input.COGS / 365) * increaseInCreditorsDays)
										)
									).toLocaleString('en-GB', {
										style: 'currency',
										currency: currencyLabel,
										minimumFractionDigits,
										maximumFractionDigits
									})} */}

									{/* asked to copy the value from the previous accordion on Dec 3rd */}
									{totalImpactOnValuationValue.toLocaleString('en-GB', {
										style: 'currency',
										currency: currencyLabel,
										minimumFractionDigits,
										maximumFractionDigits
									})}
								</b>
							</small>
						</li>
						<li className={styles.rowEmphasis}>
							<small>
								<b>Enhanced Business Value Indicator</b>
							</small>
							<small>
								<b>{(
									weightedAverageEBITDA * ebitdaValue -
									lessTotalDebt +
									(+(
										+((+lastFinancial.input.Revenue * +priceIncreaseIndex) / 100) +
										+((+lastFinancial.input['Gross Profit'] * +volumeIncreaseIndex) / 100) +
										+((+lastFinancial.input.COGS * +cogsIndex) / 100) +
										+(
											((+lastFinancial.input['Gross Profit'] - +lastFinancial.input.EBIT) *
												+overheadReductionIndex) /
											100
										)
									) *
										ebitdaValue +
										+(
											+((+lastFinancial.input.Revenue / 365) * debtorsDayReduction) +
											+((+lastFinancial.input.Revenue / 365) * reductionWipDays) +
											+((+lastFinancial.input.COGS / 365) * increaseInCreditorsDays)
										))
								).toLocaleString('en-GB', {
									style: 'currency',
									currency: currencyLabel,
									minimumFractionDigits,
									maximumFractionDigits
								})}</b>
							</small>
						</li>
					</ul>
					{/* </Typography> */}
				</AccordionDetails>
			</Accordion>
			<p style={{ fontSize: '0.925rem', marginTop: '10px' }}>
				💡 <b>Tip</b>: Use this insight to get investor ready.
			</p>
		</div>
	);
};

export default MoneyForCeosBusinessAccordion;
