import { useRecoilValue } from 'recoil';
import { useTranslation } from 'react-i18next';
import { authList } from '../../../store/authList';
import { authType } from '../../../assets/data';
import { Button, ExcelDownButton, ViewTableInfo } from '../index';

const TableHeader = ({
									 config,
									 tableRef,
									 total,
									 total_all,
									 handleOrderBy,
									 handlePageSize,
									 selectedRows = [],
									 onAction,
									 navigate,
									 pagination,
									 goToNextPage,
									 goToPrevPage
								 }) => {
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();

	const handleButtonClick = (button, e) => {
		e?.preventDefault();

		if (button.action === 'navigate' && button.navigateTo && navigate) {
			navigate(button.navigateTo);
			return;
		}

		if (onAction) {
			onAction(button.action, button.id);
		}
	};

	const renderButton = (button, index) => {
		const hasAuth = button.requiredAuth ?
			userInfo.auth_list?.some(auth => auth.id === authType[button.requiredAuth]) :
			true;

		if (!hasAuth) return null;

		if (button.component === 'ExcelDownButton') {
			return (
				<ExcelDownButton
					key={index}
					tableRef={tableRef}
					fileName={button.props?.fileName ? t(button.props.fileName) : ''}
				/>
			);
		}

		const buttonTheme = (button.disableWhen === 'noSelection' && selectedRows.length === 0) || button.disableWhen === 'disable'
			? 'disable'
			: button.theme;

		return (
			<Button
				key={index}
				theme={buttonTheme}
				text={button.text}
				handleClick={(e) => handleButtonClick(button, e)}
				disabled={button.disableWhen === 'disable'}
			/>
		);
	};

	return (
		<ViewTableInfo
			total={total}
			total_all={total_all}
			handleOrderBy={handleOrderBy}
			handlePageSize={handlePageSize}
			orderType={config.orderType}
			pageType={config.pageType}
			countType={config.countType}
			pagination={pagination}
			goToNextPage={goToNextPage}
			goToPrevPage={goToPrevPage}
		>
			{config.buttons.map(renderButton)}
		</ViewTableInfo>
	);
};

export default TableHeader;