import AuthCheckBox from '../common/input/AuthCheckBox';
import CheckBox from '../common/input/CheckBox';
import { isGroupFullySelected, isItemDisabled } from '../../utils';

const AuthGroupRows = ({ group, selectedPermissions, onPermissionChange }) => {
	const handleGroupSelect = () => {
		const allPermissions = group.items.flatMap(item =>
			Object.values(item.permissions)
		);

		const isAllSelected = allPermissions.every(id =>
			selectedPermissions.includes(id)
		);

		onPermissionChange(group.id, isAllSelected ? 'none' : 'all');
	};

	return group.items.map((item, index) => (
		<tr key={item.id} className={index === 0 ? 'table-line' : ''}>
			{index === 0 && (
				<>
					<td rowSpan={group.items.length}>
						<AuthCheckBox
							id={group.id}
							handleCheck={handleGroupSelect}
							checked={isGroupFullySelected(group, selectedPermissions)}
						/>
					</td>
					<td rowSpan={group.items.length}>{group.title}</td>
				</>
			)}
			<td>{item.title}</td>
			<td>
				<AuthCheckBox
					id={item.permissions.read?.toString()}
					name={group.id}
					checked={selectedPermissions.includes(item.permissions.read)}
					setData={(e) => onPermissionChange(group.id, e.target.id)}
					disabled={isItemDisabled(item, selectedPermissions)}
				/>
			</td>
			<td>
				{item.permissions.confirm ? (
					<AuthCheckBox
						id={item.permissions.confirm?.toString()}
						name={group.id}
						checked={selectedPermissions.includes(item.permissions.confirm)}
						setData={(e) => onPermissionChange(group.id, e.target.id)}
					/>
				) : (
					<CheckBox disabled={true} />
				)}
			</td>
			<td>
				{item.permissions.update ? (
					<AuthCheckBox
						id={item.permissions.update?.toString()}
						name={group.id}
						checked={selectedPermissions.includes(item.permissions.update)}
						setData={(e) => onPermissionChange(group.id, e.target.id)}
					/>
				) : (
					<CheckBox disabled={true} />
				)}
			</td>
			<td>
				{item.permissions.delete ? (
					<AuthCheckBox
						id={item.permissions.delete?.toString()}
						name={group.id}
						checked={selectedPermissions.includes(item.permissions.delete)}
						setData={(e) => onPermissionChange(group.id, e.target.id)}
					/>
				) : (
					<CheckBox disabled={true} />
				)}
			</td>
		</tr>
	));
};

export default AuthGroupRows;