/* eslint-disable react/destructuring-assignment */
/* eslint-disable react/jsx-no-constructed-context-values */
import type { SelectChangeEvent } from '@mui/material';
import axios from 'axios';
import { useContext, useReducer, useState } from 'react';
import type React from 'react';
import type { ChangeEvent, ReactNode } from 'react';

import environment from '../../Environments/environment';
import companyDropdownPredefinedValues from '../../Pages/Companies/Companies.helper';
import type { AddCompanyModel } from '../../Pages/Companies/Components/AddNewCompany';
import type { CompanyDbModel } from '../../Pages/Companies/Components/CompaniesComponents.helper';
import styles from '../../Pages/Companies/Components/CompaniesList.module.scss';
import type { GlobalStateModel } from '../global/GlobalState-context';
import { GlobalStateContext } from '../global/GlobalState-context';
import checkForEmptyCompanyValues, {
	CompaniesContext,
	companiesInitialState,
	companyReducerHelper,
	createCompanyRequestHandler
} from './company-context-helper';
import type { Action, CompaniesStateInterface } from './company-context-helper';

export interface FindIndustryInterface {
	value: string;
	label: string;
	id: number | null;
}

const CompaniesContextProvider: React.FC<{ children: ReactNode }> = (props: {
	children: ReactNode;
}) => {
	const globalContext: GlobalStateModel = useContext<GlobalStateModel>(GlobalStateContext);
	const { apiUrl, backendRoutes } = environment;
	function companyReducer(state: CompaniesStateInterface, action: Action): CompaniesStateInterface {
		return companyReducerHelper(state, action);
	}

	const [companyInputs, dispatchCompanyInputs] = useReducer<
		React.Reducer<CompaniesStateInterface, Action>
	>(companyReducer, companiesInitialState);
	const removeTabClass = {
		active: styles.addOrRemoveMessage,
		nonActive: styles.addOrRemoveMessageNonActive
	};
	const [errorMessage, setErrorMessage] = useState<{
		companyName: string;
		industryType: string;
	}>({
		industryType: '',
		companyName: ''
	});
	const [addOrRemoveCompanyClass, setAddOrRemoveCompanyClass] = useState<string>(
		removeTabClass.nonActive
	);
	const [createdCompany, setCreatedCompany] = useState<AddCompanyModel>({
		company_id: '',
		company_name: '',
		currency_symbol: '',
		industry_id: 0,
		company_reg_number: 0,
		industry_type: ''
	});

	const globalState: GlobalStateModel = useContext(GlobalStateContext);

	function addCompanyHandler(isChecked: boolean) {
		dispatchCompanyInputs({
			type: 'IS_LIST_ON',
			value: !isChecked
		});
	}
	function editCompanyHandler(selectedCompanyId: string): void {
		const itemForEditArray = (globalState.companies as CompanyDbModel[]).filter(
			(item) => item.company_id === selectedCompanyId
		);
		const itemForEdit = itemForEditArray[0];
		const industryIdToString = companyDropdownPredefinedValues.industry.find(
			(item) => item.id === itemForEdit.industry_id
		);
		console.log(itemForEdit, industryIdToString);
		dispatchCompanyInputs({
			type: 'EDIT_MODE',
			value: true
		});
		dispatchCompanyInputs({
			type: 'COMPANY_FOR_EDIT',
			value: itemForEdit
		});
		dispatchCompanyInputs({
			type: 'COMPANY_NAME',
			value: itemForEdit.company_name
		});
		dispatchCompanyInputs({
			type: 'INDUSTRY_TYPE',
			value: itemForEdit.industry_type
		});
		dispatchCompanyInputs({
			type: 'CURRENCY',
			value:
				typeof itemForEdit.currency_symbol === 'string'
					? itemForEdit.currency_symbol
					: itemForEdit.currency_symbol.label
		});
		dispatchCompanyInputs({
			type: 'INDUSTRY',
			value: industryIdToString?.value as string
		});
		dispatchCompanyInputs({
			type: 'COMPANY_ID',
			value: itemForEdit.company_id
		});
		dispatchCompanyInputs({
			type: 'COMPANY_REG_NUMBER',
			value: itemForEdit.company_reg_number
		});
	}
	function listCompanyHandler(event: CompanyDbModel[]): void {
		dispatchCompanyInputs({
			type: 'COMPANIES',
			value: event
		});
	}
	function cancelCompanyHandler(): void {
		dispatchCompanyInputs({
			type: 'EDIT_MODE',
			value: false
		});
		dispatchCompanyInputs({
			type: 'RESET',
			value: ''
		});
	}

	// should not be in use
	async function addNewCompanyHandler() {
		// TOREWVIEW: why is it necessary to refresh the companies list
		// from DB before we add new company?
		// globalContext.getCompaniesHandler();
		// dispatchCompanyInputs({
		// 	type: 'EDIT_MODE',
		// 	value: false
		// });
		// const { industryType, currency, companyName, industry, companyRegNumber } = companyInputs;
		// const randomIdNumber1: number = Math.random() * 100;
		// const randomIdNumber2: number = Math.random() * 100;
		// const companyId = `${randomIdNumber1}${randomIdNumber2}`;
		// localStorage.setItem('createdCompanyId', companyId);
		// const findIndustry: FindIndustryInterface | undefined =
		// 	companyDropdownPredefinedValues.industry.find((item) => industry === item.value);
		// dispatchCompanyInputs({
		// 	type: 'COMPANY_ID',
		// 	value: companyId.toString()
		// });
		// checkForEmptyCompanyValues(companyName, findIndustry, setErrorMessage);
		// if (companyName && findIndustry?.value) {
		// 	const newCompany: AddCompanyModel = {
		// 		company_name: companyName,
		// 		currency_symbol: currency,
		// 		industry_type: industryType,
		// 		company_id: companyId,
		// 		company_reg_number: companyRegNumber,
		// 		industry_id: findIndustry?.id as number
		// 	};
		// 	setCreatedCompany(newCompany);
		// 	localStorage.setItem('selectedCompany', JSON.stringify(newCompany));
		// 	// let companyFromDB;
		// 	await createCompanyRequestHandler(newCompany)
		// 		.then((response) => {
		// 			const companyData = JSON.parse(response.data as string);
		// 			globalContext.getCompaniesHandler(companyData);
		// 			dispatchCompanyInputs({
		// 				type: 'ADD_REMOVE_MESSAGE',
		// 				value: response.data
		// 			});
		// 		})
		// 		.catch((error: Error) => {
		// 			if (error.message) {
		// 				dispatchCompanyInputs({
		// 					type: 'ADD_REMOVE_MESSAGE',
		// 					value: error.message
		// 				});
		// 			}
		// 		});
		// 	dispatchCompanyInputs({
		// 		type: 'RESET',
		// 		value: ''
		// 	});
		// }
		// setAddOrRemoveCompanyClass(removeTabClass.active);
		// return new Promise((resolve) => {
		// 	resolve(true);
		// });
	}

	// should not be in use
	function saveEditedCompany(): void {
		// const { industryType, currency, companyName, industry, companyId, companyRegNumber } =
		// 	companyInputs;
		// const currencySymbol = companyDropdownPredefinedValues.currency.find((item) =>
		// 	item.value === currency ? item.label : null
		// );
		// localStorage.setItem('currency', currencySymbol?.label as string);
		// const findIndustry: FindIndustryInterface | undefined =
		// 	companyDropdownPredefinedValues.industry.find((item) => industry === item.value);
		// checkForEmptyCompanyValues(companyName, findIndustry, setErrorMessage);
		// if (!findIndustry) {
		// 	return;
		// }
		// if (companyName && findIndustry.value !== 'null') {
		// 	const editedCompany: AddCompanyModel = {
		// 		company_name: companyName,
		// 		currency_symbol: currency,
		// 		industry_type: industryType,
		// 		company_id: companyId,
		// 		company_reg_number: companyRegNumber,
		// 		industry_id: findIndustry?.id as number
		// 	};
		// 	axios
		// 		.post(apiUrl + backendRoutes.company, editedCompany)
		// 		.then((response) => {
		// 			dispatchCompanyInputs({
		// 				type: 'ADD_REMOVE_MESSAGE',
		// 				value: response.data
		// 			});
		// 		})
		// 		.catch((error: Error) => {
		// 			if (error.message) {
		// 				dispatchCompanyInputs({
		// 					type: 'ADD_REMOVE_MESSAGE',
		// 					value: error.message
		// 				});
		// 			}
		// 		});
		// 	dispatchCompanyInputs({
		// 		type: 'RESET',
		// 		value: ''
		// 	});
		// 	dispatchCompanyInputs({
		// 		type: 'EDIT_MODE',
		// 		value: false
		// 	});
		// 	dispatchCompanyInputs({
		// 		type: 'RESET',
		// 		value: ''
		// 	});
		// 	setAddOrRemoveCompanyClass(removeTabClass.active);
		// }
	}

	function deleteHandler(event: string): void {
		axios
			.post(apiUrl + backendRoutes.removeCompany, {
				company_id: event
			})
			.then((response) => {
				dispatchCompanyInputs({
					type: 'ADD_REMOVE_MESSAGE',
					value: response.data
				});
			})
			.catch((error: Error) => {
				if (error.message) {
					dispatchCompanyInputs({
						type: 'ADD_REMOVE_MESSAGE',
						value: error.message
					});
				}
				dispatchCompanyInputs({
					type: 'RESET',
					value: ''
				});
			});
		(globalState.companies as CompanyDbModel[]).filter((item) => {
			if (item.company_id === event) {
				dispatchCompanyInputs({
					type: 'COMPANIES',
					value: item
				});
			}
			return item.company_id === event;
		});
		setAddOrRemoveCompanyClass(removeTabClass.active);
		globalContext.getCompaniesHandler();
	}

	function switchHandler(): void {
		dispatchCompanyInputs({
			type: 'SWITCH_TO_FORM',
			value: !companyInputs.switchToForm
		});
	}

	function companyNameHandler(event: ChangeEvent<HTMLInputElement>): void {
		dispatchCompanyInputs({
			type: 'COMPANY_NAME',
			value: event.target.value
		});
	}
	function subscriberHandler(event: ChangeEvent<HTMLInputElement>): void {
		dispatchCompanyInputs({
			type: 'SUBSCRIBER',
			value: event.target.value
		});
	}

	function industryTypeHandler(event: SelectChangeEvent<string>): void {
		dispatchCompanyInputs({
			type: 'INDUSTRY_TYPE',
			value: event.target.value
		});
	}

	function industryHandler(event: SelectChangeEvent<string>): void {
		dispatchCompanyInputs({
			type: 'INDUSTRY',
			value: event.target.value
		});
	}

	function roleHandler(event: SelectChangeEvent<string>): void {
		dispatchCompanyInputs({
			type: 'ROLE',
			value: event.target.value
		});
	}

	function currencyHandler(event: SelectChangeEvent<string>): void {
		dispatchCompanyInputs({
			type: 'CURRENCY',
			value: event.target.value
		});
	}
	function companyRegNumberHandler(event: SelectChangeEvent<string>): void {
		dispatchCompanyInputs({
			type: 'COMPANY_REG_NUMBER',
			value: event.target.value
		});
	}
	function resetErrorMessageHandler() {
		setErrorMessage({
			industryType: '',
			companyName: ''
		});
	}

	const {
		isListOn,
		companyForEdit,
		companyName,
		industryType,
		industry,
		currency,
		switchToForm,
		addRemoveMessage,
		editMode,
		companyId,
		companyRegNumber,
		subscriber
	} = companyInputs;
	const contextValue = {
		addCompany: addCompanyHandler,
		isChecked: isListOn,
		editCompany: editCompanyHandler,
		companyForEdit,
		listCompany: listCompanyHandler,
		addNewCompany: addNewCompanyHandler,
		editMode,
		deleteHandler,
		addRemoveMessage,
		switchToForm,
		switchHandler,
		cancelCompanyHandler,
		companyNameHandler,
		industryTypeHandler,
		industryHandler,
		roleHandler,
		currencyHandler,
		companyName,
		industryType,
		industry,
		currency,
		companyId,
		saveEditedCompany,
		addOrRemoveCompanyClass,
		errorMessage,
		resetErrorMessageHandler,
		createdCompany,
		companyRegNumber,
		companyRegNumberHandler,
		subscriberHandler,
		subscriber
	};
	return (
		<CompaniesContext.Provider value={contextValue}>{props.children}</CompaniesContext.Provider>
	);
};

export default CompaniesContextProvider;
