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 {Sites} from "/imports/api/sites";

const cssEditorField = {
	margin: '0.6rem 0',
}
const cssFieldContainer = {
	display: 'flex',
	flexDirection: 'column',
	backgroundColor: '#DDD',
	padding: '0.5rem',
	border: '1px solid #999',
	borderRadius: '0.2rem',
}
const cssButtonContainer = {
	display: 'flex',
	gap: '1rem',
	justifyContent: 'flex-end'
}

const SiteEditor = ({value, close}) => {
	const [name, setName] = useState(value.name || "")
	const [externalId, setExternalId] = useState(value.externalId || "")

	const applyChanges = () => {
		close()
		//TODO Should invert this and only close if there was success on the server.
		if(value._id)
			Meteor.call("sites.update", value._id, name, externalId);
		else
			Meteor.call("sites.add", name, externalId);
	}
	const rejectChanges = () => {
		close()
	}

	return (
		<div style={cssFieldContainer}>
			<h1>Site Editor</h1>
			<TextField style={cssEditorField} variant="standard" label="Name" value={name} onChange={(e) => {setName(e.target.value)}}/>
			<TextField style={cssEditorField} variant="standard" label="External ID" value={externalId} onChange={(e) => {setExternalId(e.target.value)}}/>
			<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 () => {
	Meteor.subscribe('sites');

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

	const columns = [
		{
			name: "Name",
			value: (row) => row.name,
		},
		{
			name: "External ID",
			value: (row) => row.externalId,
		},
	]

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

	return (
		<>
			<SimpleTable rows={sites} columns={columns} options={options}/>
		</>
	)
}