import { Meteor } from 'meteor/meteor';
import React, { useState } from 'react';
import { useTracker } from 'meteor/react-meteor-data';
import _ from 'lodash';
import SimpleTable from "/imports/ui/util/SimpleTable";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import {Staff} from "/imports/api/staff";
import {Sites} from "/imports/api/sites";

const cssSitesSelect = {
	margin: '0.6rem 0',
	minWidth: '20rem',
}
const cssFieldColumnContainer = {
	display: 'flex',
	flexDirection: 'column',
	backgroundColor: '#DDD',
	padding: '0.5rem',
	border: '1px solid #999',
	borderRadius: '0.2rem'
}
const cssGridFieldContainer = {
	display: 'grid',
	gridTemplateColumns: "1fr 1fr 1fr",
	columnGap: '1rem',
	rowGap: '0.4rem',
	marginBottom: '1.5rem'
}
const cssButtonContainer = {
	display: 'flex',
	gap: '1rem',
	justifyContent: 'flex-end'
}

const StaffEditor = ({value, close, defaultSiteId}) => {
	const [email, setEmail] = useState(value.email || "")
	const [id, setId] = useState(value.id || "")
	const [firstName, setFirstName] = useState(value.firstName || "")
	const [lastName, setLastName] = useState(value.lastName || "")
	const [siteId, setSiteId] = useState(value.siteId ? value.siteId : defaultSiteId)

	const {sites} = useTracker(() => {
		let sites = Sites.find({}).fetch();

		return {sites}
	});

	if(!siteId && sites && sites.length > 0) {
		setSiteId(sites[0]._id)
	}

	const applyChanges = () => {
		close()
		//TODO Should invert this and only close if there was success on the server.
		if(value._id)
			Meteor.call("staff.update", value._id, id, firstName, lastName, email, siteId);
		else
			Meteor.call("staff.add", id, firstName, lastName, email, siteId);
	}
	const rejectChanges = () => {
		close()
	}

	return (
		<div style={cssFieldColumnContainer}>
			<h1>Staff Editor</h1>
			<div style={cssGridFieldContainer}>
				<TextField variant="standard" label="ID" value={id} onChange={(e) => {setId(e.target.value)}}/>
				<TextField variant="standard" label="Email" value={email} onChange={(e) => {setEmail(e.target.value)}}/>
				<div/>
				<TextField variant="standard" label="First Name" value={firstName} onChange={(e) => {setFirstName(e.target.value)}}/>
				<TextField variant="standard" label="Last Name" value={lastName} onChange={(e) => {setLastName(e.target.value)}}/>
				<TextField select variant="standard" label="Site" value={siteId} onChange={(e) => {setSiteId(e.target.value)}}>
					{sites.map((next, i) => {
						return <MenuItem key={next._id} value={next._id}>{next.name}</MenuItem>
					})}
				</TextField>
			</div>
			<div style={cssButtonContainer}>
				<Button variant="contained" className="button accept-button" onClick={applyChanges}>Accept</Button>
				<Button variant="outlined" className="button reject-button" onClick={rejectChanges}>Reject</Button>
			</div>
		</div>
	)
}

export default () => {
	const siteAll = {_id: 0, name: "All"}
	const [site, setSite] = useState(siteAll._id)

	Meteor.subscribe('sites');
	Meteor.subscribe('staff');

	const {sites} = useTracker(() => {
		const sites = Sites.find({}).fetch();

		sites.push(siteAll);

		return {sites}
	});

	const {staff} = useTracker(() => {
		const staffQuery = site === siteAll._id ? {} : {siteId: site}
		let staff = Staff.find(staffQuery).fetch();

		return {staff}
	});

	const columns = [
		{
			name: "ID",
			value: (row) => row.id,
			descendingComparator: (a, b) => {
				if(a.id === b.id) return 0
				else if(!a.id) return -1
				else if(!b.id) return 1
				else if(a.id.length < b.id.length) return 1
				else if(a.id.length > b.id.length) return -1
				else if(b.id < a.id) return -1
				else return 1
			}
		},
		{
			name: "Email",
			value: (row) => row.email,
		},
		{
			name: "First Name",
			value: (row) => row.firstName,
		},
		{
			name: "Last Name",
			value: (row) => row.lastName,
		},
	]

	const options = {
		key: (row) => row._id,
		editor: (row, close) => {return (<StaffEditor value={row} close={close} defaultSiteId={site}/>)},
		add: true,
		maxHeight: '40rem',
		keyHandler: (e, selected) => {
			if(selected && selected._id && e.key === "Delete") {
				Meteor.call("staff.remove", selected._id);
			}
		}
	}

	return (
		<>
			<TextField label="Site" style={cssSitesSelect} select variant="standard" value={site} onChange={(e)=>{setSite(e.target.value)}}>
				{sites.map((next, i) => {
					return <MenuItem key={next._id} value={next._id}>{next.name}</MenuItem>
				})}
			</TextField>
			<SimpleTable rows={staff} columns={columns} options={options}/>
		</>
	)
}