import { Meteor } from 'meteor/meteor';
import React, { useState } from 'react';
import { useTracker } from 'meteor/react-meteor-data';
import _ from 'lodash';
import Button from '@mui/material/Button';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import classNames from 'classnames';

Meteor.subscribe('allUsers');
Meteor.subscribe('allRoleAssignments');

let UsersTable = ({rows}) => {
	const [selected, setSelected] = useState(undefined);
	
	let selectRow = (e, row) => {
		setSelected(row);
	}

	const [edited, setEdited] = useState(undefined);
	const [permissions, setPermissions] = useState(undefined);
	
	let editRow = (e, row) => {
		if(row) {
			setPermissions({
				isAdmin: Roles.userIsInRole(row, "admin", {anyScope: true}),
				laptopManagement: Roles.userIsInRole(row, "laptop-management", {anyScope: true}),
			})
		} else setPermissions(undefined)
		setEdited(row);
	}
	
	let togglePermission = (permission) => {
		permissions[permission] = !permissions[permission]
		setPermissions({...permissions})
	}
	
	let applyChanges = (e) => {
		let roles = [];

		if(permissions.isAdmin) {
			roles.push('admin');
		}
		else {
			if(permissions.laptopManagement) {
				roles.push('laptop-management');
			}
		}

		Meteor.call("users.setUserRoles", edited._id, roles);
		setEdited(undefined);
	}
	
	let rejectChanges = (e) => {
		setEdited(undefined)
	}
	
	return (
		<TableContainer className="userTable" component={Paper}>
			<Table size="small" aria-label="User Table">
				<TableHead className="sticky">
					<TableRow>
						<TableCell className="headerCell">Name</TableCell>
						<TableCell className="headerCell">Email</TableCell>
						<TableCell className="headerCell">Roles</TableCell>
					</TableRow>
				</TableHead>
				<TableBody>
					{rows.map((row)=>(
						<TableRow key={row._id} className={classNames({tableRow: true, selected: (!edited || edited._id !== row._id) && selected && selected._id === row._id})} onDoubleClick={(e) => {editRow(e, row)}} onClick={(e) => selectRow(e, row)}>
							{edited && edited._id === row._id ?
								<TableCell className="userEditorContainer" colSpan="3">
									<div className="userEditorGrid">
										<label style={{gridColumn: "1/4", fontWeight: "800", borderBottom: "2px solid #888", marginBottom: "0.5rem"}}>{edited.profile.name}</label>
										<FormControlLabel style={{gridColumn: "1/4"}} control={<Checkbox checked={permissions && permissions.isAdmin} onChange={() => togglePermission('isAdmin')}/>} label="Administrator"/>
										<div className="insetPermissions" style={{gridColumn: "1/4"}}>
											<FormControlLabel control={<Checkbox disabled={permissions && permissions.isAdmin} checked={permissions && permissions.laptopManagement} onChange={() => togglePermission('laptopManagement')}/>} label="Laptop Management"/>
										</div>
										<Button variant="contained" style={{gridColumn: '2/2'}} className="button accept-button" onClick={applyChanges}>Accept</Button>
										<Button type="outlined" style={{gridColumn: '3/3'}} className="button reject-button" onClick={rejectChanges}>Reject</Button>
									</div>
								</TableCell>
							: <>
								<TableCell align="left">{row.profile.name}</TableCell>
								<TableCell align="left">{row.services && row.services.google ? row.services.google.email : ""}</TableCell>
								<TableCell align="left">{row.roles}</TableCell>
							</>
						}
						</TableRow>
					))}
				</TableBody>
			</Table>
		</TableContainer>
	)
}

/*
 * Separate the Meteor calls as much as possible to avoid them being run repeatedly unnecessarily (were being run on every selection in the table).
 */
export default () => {
	const {rows} = useTracker(() => {
		const rows = Meteor.users.find({}).fetch();

		for(let row of rows) {
			row.roles = Roles.getRolesForUser(row, {anyScope: true})
		}

		return {
			rows
		}
	});

	return <UsersTable rows={rows}/>
}