import type { IndustryModel } from '../../Store/Financials/financialsContext.helper';
import type { CompanyDbModel } from '../Companies/Components/CompaniesComponents.helper';
import type {
	Action,
	FinancialsModel
} from '../Financials/Components/FinancialsForm/FinancialsForm.helper';
import { formDefaultValues } from '../Financials/Components/FinancialsForm/FinancialsForm.helper';
import styles from '../Financials/Financials.module.scss';

export interface MoneyMultiplierContextInterface {
	priceIncreaseEbit: number;
	priceIncreaseNetCashFlow: number;
	netCashFlow: number;
	volumeIncrease: number;
	volumeIncreaseEbit: number;
	volumeIncreaseCashFlow: number;
	cogsEbit: number;
	cogsCashFlow: number;
	overheadEbit: number;
	overheadCashFlow: number;
	debtorsDayCashFlow: number;
	reductionInWip: number;
	increaseCreditorsDays: number;
	increaseDeferredRevenueDays: number;
	netCashFlowSum: number;
	ebitSum: number;
	netCashFlowEnd: number;
	ebitEnd: number;
	percentState: number;
	priceIncreasePercentEbit: number;
	volumeIncreasePercent: number;
	cogsPercent: number;
	overheadPercent: number;
	debtorsDayPercentage: number;
	reductionInWipDays: number;
	increaseInCreditorsDays: number;
	increaseInDeferredRevenueDays: number;
	ebit: number;
	endingMonth: string;
	endingYear: string;
	weightedAverageEBITDA: number;
	lessTotalDebt: number;
	equityValuation: number;
	actualEquity: number;
	ebitdaValue: number;
	priceIncreaseImpact: number;
	volumeIncreaseImpact: number;
	overheadReduction: number;
	cogsImpact: number;
	cashImpact: number;
	totalImpact: number;
	enhancedBusinessValueIndicator: number;
	impactOnMultiplierAdjustmentOnValuation: number;
	selectedFinancials: number[];
	firstMonth: string;
	lastMonth: string;
	firstYear: string;
	lastYear: string;
	profitImpactOnValuation: number;
}

export const moneyMultiplierContextDefaultValues: MoneyMultiplierContextInterface = {
	priceIncreaseEbit: 0,
	priceIncreaseNetCashFlow: 0,
	netCashFlow: 0,
	volumeIncrease: 0,
	volumeIncreaseEbit: 0,
	volumeIncreaseCashFlow: 0,
	cogsEbit: 0,
	cogsCashFlow: 0,
	overheadEbit: 0,
	overheadCashFlow: 0,
	debtorsDayCashFlow: 0,
	reductionInWip: 0,
	increaseCreditorsDays: 0,
	increaseDeferredRevenueDays: 0,
	netCashFlowSum: 0,
	ebitSum: 0,
	netCashFlowEnd: 0,
	ebitEnd: 0,
	percentState: 1,
	priceIncreasePercentEbit: 1,
	volumeIncreasePercent: 1,
	cogsPercent: 1,
	overheadPercent: 1,
	debtorsDayPercentage: 1,
	reductionInWipDays: 1,
	increaseInCreditorsDays: 1,
	increaseInDeferredRevenueDays: 1,
	ebit: 0,
	endingMonth: '',
	endingYear: '',
	weightedAverageEBITDA: 0,
	lessTotalDebt: 0,
	equityValuation: 0,
	actualEquity: 0,
	ebitdaValue: 1,
	priceIncreaseImpact: 0,
	volumeIncreaseImpact: 0,
	overheadReduction: 0,
	cogsImpact: 0,
	cashImpact: 0,
	totalImpact: 0,
	enhancedBusinessValueIndicator: 0,
	impactOnMultiplierAdjustmentOnValuation: 0,
	selectedFinancials: [],
	firstMonth: '',
	lastMonth: '',
	firstYear: '',
	lastYear: '',
	profitImpactOnValuation: 0
};

export type MoneyMultiplierForCeosContextModel = {
	editFinancial: (props: FinancialsModel | undefined) => void;
	financialForEdit: FinancialsModel | undefined;
	selectedItems: string[];
	// selectedItemsHandler: (event: string) => void;
	// unselectedItemHandler: (event: string) => void;
	isCheckedCardHandler: (first: string | undefined) => void;
	whatIsChecked: number;
	classForPopup: string;
	financialsPrepHandler: () => void;
	storageFinancialsHandler: () => void;
	netCashFlow: number;
	priceIncreaseEbit: number;
	priceIncreaseNetCashFlow: number;
	volumeIncrease: number;
	volumeIncreaseEbit: number;
	volumeIncreaseCashFlow: number;
	cogsEbit: number;
	cogsCashFlow: number;
	overheadEbit: number;
	overheadCashFlow: number;
	debtorsDayCashFlow: number;
	reductionInWip: number;
	increaseCreditorsDays: number;
	increaseDeferredRevenueDays: number;
	netCashFlowSum: number;
	ebitSum: number;
	netCashFlowEnd: number;
	ebitEnd: number;
	ebit: number;
	weightedAverageEBITDA: number;
	lessTotalDebt: number;
	equityValuation: number;
	actualEquity: number;
	setEbitdaHandler: (event: number) => void;
	ebitdaValue: number;
	priceIncreaseImpact: number;
	volumeIncreaseImpact: number;
	cogsImpact: number;
	cashImpact: number;
	totalImpact: number;
	enhancedBusinessValueIndicator: number;
	impactOnMultiplierAdjustmentOnValuation: number;
	profitImpactOnValuation: number;
	overheadReduction: number;
	getAllStates: (
		priceIncrease: number,
		volumeIncrease: number,
		cogs: number,
		overheadReduction: number,
		debtorsDayReduction: number,
		reductionWipDays: number,
		increaseInCreditorsDays: number,
		increaseInDeferredRevenueDays: number
	) => void;
	firstMonth: string;
	lastMonth: string;
	firstYear: string;
	lastYear: string;
	planHandler: (event: string) => void;
	plan: string;
	activateUser: number;
	activateUserHandler: (planName: string) => void;
	companyIdHandler: (id: string) => void;
	selectedCompanyFinancials: FinancialsModel[];
	getCompanyTypeHandler: (companyType: string) => void;
	getCompanySignHandler: (event: string) => void;
	isDemoActive: boolean;
	demoActiveHandler: (event: boolean) => void;
	companies: CompanyDbModel[];
	ebitdaHandler: (ebitda: number) => void;
	selectedIndustryForEbitda: IndustryModel;
	nextButtonHandler: () => void;
	popupClass: string;
	// loadedSelectedItemsHandler: (event: string[]) => void;
	// findSelectedFinancials: (selectedFinancials: string[]) => void;
};

export const MoneyMultiplierForCeosMainContextDefault = {
	editFinancial: (): void => {},
	financialForEdit: {
		company_id: '',
		selected: false,
		financials_id: '',
		cognito_username: '',
		input: formDefaultValues
	},
	selectedItems: [],
	selectedItemsHandler: (): void => {},
	unselectedItemHandler: (): void => {},
	isCheckedCardHandler: (): void => {},
	whatIsChecked: 0,
	classForPopup: styles.collapseContainer,
	financialsPrepHandler: (): void => {},
	storageFinancialsHandler: (): void => {},
	priceIncreasePercentageInputHandler: (): void => {},
	volumeIncreaseHandler: (): void => {},
	cogsReductionHandler: (): void => {},
	overheadReductionHandler: (): void => {},
	debtorsDayHandler: (): void => {},
	reductionInWipHandler: (): void => {},
	increaseCreditorsDaysHandler: (): void => {},
	netCashFlow: 0,
	priceIncreaseEbit: 0,
	priceIncreaseNetCashFlow: 0,
	volumeIncrease: 1,
	volumeIncreaseEbit: 1,
	volumeIncreaseCashFlow: 1,
	cogsEbit: 0,
	cogsCashFlow: 0,
	overheadEbit: 0,
	overheadCashFlow: 0,
	debtorsDayCashFlow: 1,
	reductionInWip: 1,
	increaseCreditorsDays: 1,
	increaseDeferredRevenueDays: 1,
	netCashFlowSum: 0,
	ebitSum: 0,
	netCashFlowEnd: 0,
	ebitEnd: 0,
	ebit: 1,
	weightedAverageEBITDA: 0,
	lessTotalDebt: 0,
	equityValuation: 0,
	actualEquity: 0,
	setEbitdaHandler: (): void => {},
	ebitdaValue: 1,
	priceIncreaseImpact: 0,
	volumeIncreaseImpact: 0,
	cogsImpact: 0,
	cashImpact: 0,
	totalImpact: 0,
	enhancedBusinessValueIndicator: 0,
	impactOnMultiplierAdjustmentOnValuation: 0,
	profitImpactOnValuation: 0,
	overheadReduction: 0,
	getAllStates: (): void => {},
	firstMonth: '',
	lastMonth: '',
	firstYear: '',
	lastYear: '',
	planHandler: (): void => {},
	plan: 'Basic Plan',
	activateUser: 0,
	activateUserHandler: (): void => {},
	companyIdHandler: (): void => {},
	selectedCompanyFinancials: [],
	getCompanyTypeHandler: (): void => {},
	getCompanySignHandler: (): void => {},
	isDemoActive: false,
	demoActiveHandler: (): void => {},
	companies: [],
	ebitdaHandler: (): void => {},
	selectedIndustryForEbitda: {
		name: '',
		zeroToOne: 0,
		twoToFive: 0,
		sixToTen: 0,
		id: 0
	},
	nextButtonHandler: (): void => {},
	popupClass: ''
	// loadedSelectedItemsHandler: (): void => {},
	// findSelectedFinancials: (): void => {}
};

interface LatestFinancialsInterface {
	revenue: number;
	COGS: number;
	grossProfit: number;
	tradeDebtors: number;
	stock: number;
	tradeCreditors: number;
	deferredRevenue: number;
	ebit: number;
	lastYearCogs: number;
	grossMargin: number;
	month: string;
	year: string;
	deprecation: number;
	bankLoanCurrent: number;
	bankLoanNonCurrent: number;
	totalCurrentAssets: number;
	fixedAssets: number;
	totalLiabilities: number;
	totalAssets: number;
}

export function latestFinancialsHelper(
	latestFinancials: FinancialsModel
): LatestFinancialsInterface {
	let financials: LatestFinancialsInterface = {
		revenue: 0,
		COGS: 0,
		grossProfit: 0,
		tradeDebtors: 0,
		stock: 0,
		tradeCreditors: 0,
		deferredRevenue: 0,
		ebit: 0,
		lastYearCogs: 0,
		grossMargin: 0,
		month: '',
		year: '',
		deprecation: 0,
		bankLoanCurrent: 0,
		bankLoanNonCurrent: 0,
		totalCurrentAssets: 0,
		fixedAssets: 0,
		totalLiabilities: 0,
		totalAssets: 0
	};
	if (latestFinancials && latestFinancials.input !== undefined && latestFinancials.input) {
		financials = {
			revenue: +latestFinancials.input.Revenue,
			COGS: +latestFinancials.input.COGS,
			grossProfit: +latestFinancials.input['Gross Profit'],
			tradeDebtors: +latestFinancials.input['Trade Debtors'],
			stock: +latestFinancials.input.Stock,
			tradeCreditors: +latestFinancials.input['Trade Creditors'],
			deferredRevenue: +latestFinancials.input['Deferred Revenue'],
			ebit: +latestFinancials.input.EBIT,
			lastYearCogs: +latestFinancials.input.COGS,
			grossMargin:
				(+latestFinancials.input['Gross Profit'] / +latestFinancials.input.Revenue) * 100,
			month: latestFinancials.input['Month Ending'],
			year: latestFinancials.input['Year Ending'],
			deprecation: +latestFinancials.input.Depreciation,
			bankLoanCurrent: +latestFinancials.input['Additional Bank Loans - Current'],
			bankLoanNonCurrent: +latestFinancials.input['Additional Bank Loans - Non Current'],
			totalCurrentAssets: +latestFinancials.input['Additional Total Current Assets'],
			fixedAssets: +latestFinancials.input['Additional Fixed Assets'],
			totalLiabilities: +latestFinancials.input['Additional Total Liabilities'],
			totalAssets: +latestFinancials.input['Additional Total Assets']
		};
	}
	return financials;
}

export function reducerHandlerHelper(
	state: MoneyMultiplierContextInterface,
	action: Action,
	initialStateMMC: MoneyMultiplierContextInterface
): MoneyMultiplierContextInterface {
	switch (action.type) {
		case 'PRICE_INCREASE_PERCENT_EBIT':
			return {
				...state,
				priceIncreasePercentEbit: +action.value
			};
		case 'EBIT':
			return {
				...state,
				ebit: +action.value
			};
		case 'PRICE_INCREASE_NET_CASH_FLOW':
			return {
				...state,
				priceIncreaseNetCashFlow: +action.value
			};
		case 'PRICE_INCREASE_EBIT':
			return {
				...state,
				priceIncreaseEbit: +action.value
			};
		case 'VOLUME_INCREASE':
			return {
				...state,
				volumeIncrease: +action.value
			};
		case 'VOLUME_INCREASE_EBIT':
			return {
				...state,
				volumeIncreaseEbit: +action.value
			};
		case 'VOLUME_INCREASE_NET_CASH_FLOW':
			return {
				...state,
				volumeIncreaseCashFlow: +action.value
			};
		case 'NET_CASH_FLOW':
			return {
				...state,
				netCashFlow: +action.value
			};
		case 'COGS_EBIT':
			return {
				...state,
				cogsEbit: +action.value
			};
		case 'COGS_CASH_FLOW':
			console.log('COGS_CASH_FLOW', { ...state }, +action.value);
			return {
				...state,
				cogsCashFlow: +action.value
			};
		case 'OVERHEAD_EBIT':
			return {
				...state,
				overheadEbit: +action.value
			};
		case 'OVERHEAD_CASH_FLOW':
			return {
				...state,
				overheadCashFlow: +action.value
			};
		case 'OVERHEAD_REDUCTION':
			return {
				...state,
				overheadReduction: +action.value
			};
		case 'DEBTORS_DAY_CASH_FLOW':
			return {
				...state,
				debtorsDayCashFlow: +action.value
			};
		case 'REDUCTION_IN_WIP':
			return {
				...state,
				reductionInWip: +action.value
			};
		case 'INCREASE_CREDITORS_DAYS':
			return {
				...state,
				increaseCreditorsDays: +action.value
			};
		case 'INCREASE_DEFERRED_REVENUE_DAYS':
			return {
				...state,
				increaseDeferredRevenueDays: +action.value
			};
		case 'NET_CASH_FLOW_SUM':
			return {
				...state,
				netCashFlowSum: +action.value
			};
		case 'NET_CASH_FLOW_END':
			return {
				...state,
				netCashFlowEnd: +action.value
			};
		case 'EBIT_END_SUM':
			return {
				...state,
				ebitEnd: +action.value
			};
		case 'EBIT_SUM':
			return {
				...state,
				ebitSum: +action.value
			};
		case 'PERCENT_STATE':
			return {
				...state,
				percentState: +action.value
			};
		case 'PRICE_INCREASE_PERCENT_EBIT_INPUT':
			return {
				...state,
				priceIncreasePercentEbit: +action.value
			};
		case 'VOLUME_INCREASE_PERCENT_INPUT':
			return {
				...state,
				volumeIncreasePercent: +action.value
			};
		case 'COGS_PERCENT_INPUT':
			return {
				...state,
				cogsPercent: +action.value
			};
		case 'OVERHEAD_PERCENT_INPUT':
			return {
				...state,
				overheadPercent: +action.value
			};
		case 'DEBTORS_DAY_PERCENT_INPUT':
			return {
				...state,
				debtorsDayPercentage: +action.value
			};
		case 'REDUCTION_IN_WIP_DAYS_INPUT':
			return {
				...state,
				reductionInWipDays: +action.value
			};
		case 'INCREASE_CREDITORS_DAYS_INPUT':
			return {
				...state,
				increaseInCreditorsDays: +action.value
			};
		case 'INCREASE_IN_DEFERRED_REVENUE_DAYS_INPUT':
			return {
				...state,
				increaseInDeferredRevenueDays: +action.value
			};
		case 'ENDING_MONTH':
			return {
				...state,
				endingMonth: action.value.toString()
			};
		case 'ENDING_YEAR':
			return {
				...state,
				endingYear: action.value.toString()
			};
		case 'WEIGHT_AVERAGE_EBITDA':
			return {
				...state,
				weightedAverageEBITDA: +action.value
			};
		case 'LESS_TOTAL_DEBT':
			return {
				...state,
				lessTotalDebt: +action.value
			};
		case 'EQUITY_VALUATION':
			return {
				...state,
				equityValuation: +action.value
			};
		case 'ACTUAL_EQUITY':
			return {
				...state,
				actualEquity: +action.value
			};
		case 'EBITDA_VALUE':
			return {
				...state,
				ebitdaValue: +action.value
			};
		case 'PRICE_INCREASE_IMPACT':
			return {
				...state,
				priceIncreaseImpact: +action.value
			};
		case 'VOLUME_INCREASE_IMPACT':
			return {
				...state,
				volumeIncreaseImpact: +action.value
			};
		case 'COGS_IMPACT':
			return {
				...state,
				cogsImpact: +action.value
			};
		case 'CASH_IMPACT':
			return {
				...state,
				cashImpact: +action.value
			};
		case 'TOTAL_IMPACT':
			return {
				...state,
				totalImpact: +action.value
			};
		case 'PROFIT_IMPACT_ON_VALUATION':
			return {
				...state,
				profitImpactOnValuation: +action.value
			};
		case 'IMPACT_ON_MULTIPLIER_ADJUSTMENT_ON_VALUATION':
			return {
				...state,
				impactOnMultiplierAdjustmentOnValuation: +action.value
			};
		case 'ENHANCED_BUSINESS_VALUE_INDICATOR':
			return {
				...state,
				enhancedBusinessValueIndicator: +action.value
			};
		case 'SELECTED_FINANCIALS':
			return {
				...state,
				selectedFinancials: [...state.selectedFinancials, +action.value]
			};
		case 'UNSELECTED_FINANCIALS':
			return {
				...state,
				selectedFinancials: state.selectedFinancials.filter((item) => item !== +action.value)
			};
		case 'FIRST_MONTH':
			return {
				...state,
				firstMonth: action.value.toString()
			};
		case 'LAST_MONTH':
			return {
				...state,
				lastMonth: action.value.toString()
			};
		case 'FIRST_YEAR':
			return {
				...state,
				firstYear: action.value.toString()
			};
		case 'LAST_YEAR':
			return {
				...state,
				lastYear: action.value.toString()
			};
		default:
			return initialStateMMC;
	}
}
