import { Meteor } from 'meteor/meteor';
import React, { useState, useEffect } from 'react';
import { useTracker } from 'meteor/react-meteor-data';
import { useTheme } from '@mui/material/styles';
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 Chip from '@mui/material/Chip';
import MenuItem from '@mui/material/MenuItem';
import {InputLabel, List, ListItem, ListItemButton, ListItemText} from "@mui/material";
import Box from "@mui/material/Box";
import OutlinedInput from '@mui/material/OutlinedInput';
import FormControl from '@mui/material/FormControl';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import {Assets, conditions} from "/imports/api/assets";
import {AssetTypes} from "/imports/api/asset-types";
import {Students} from "/imports/api/students";
import {Staff} from "/imports/api/staff";
import {Link} from "react-router-dom";

const cssTwoColumnContainer = {
	display: 'grid',
	gridTemplateColumns: "1fr 1fr",
	columnGap: '1rem',
	rowGap: '0.4rem',
}
const cssEditorField = {
	minWidth: '10rem'
}

const AssignmentsByAsset = () => {
	const theme = useTheme();
	const [assetId, setAssetId] = useState("")

	//Dialog stuff.
	const [openUnassignDialog, setOpenUnassignDialog] = useState(false)
	const [unassignDialogEditConditionOnly, setUnassignDialogEditConditionOnly] = useState(false)
	const [unassignCondition, setUnassignCondition] = useState(conditions[2])
	const [unassignComment, setUnassignComment] = useState("")
	const [unassignConditionDetails, setUnassignConditionDetails] = useState("")

	const [assetIdInput, setAssetIdInput] = useState(undefined)


	const {foundAsset} = useTracker(() => {
		let foundAsset = null;

		if(assetId) {
			foundAsset = Assets.findOne({assetId: assetId});

			if(foundAsset) {
				foundAsset.assetType = AssetTypes.findOne({_id: foundAsset.assetTypeId})

				if(foundAsset.assigneeId)
					foundAsset.assignee = foundAsset.assigneeType === "Student" ? Students.findOne({_id: foundAsset.assigneeId}) : Staff.findOne({_id: foundAsset.assigneeId})
			}
		}

		return {foundAsset}
	});

	//This works too well.  The field always gets focus anytime anything is typed anywhere.
	// useEffect(() => {
	// 	if(assetIdInput) assetIdInput.focus()
	// })

	const unassign = (editConditionOnly) => {
		// Open the dialog to get condition and comment.
		setUnassignDialogEditConditionOnly(editConditionOnly)
		setUnassignComment("")
		setUnassignCondition(foundAsset.condition ? foundAsset.condition : conditions[2])
		setUnassignConditionDetails(foundAsset.conditionDetails || "")
		setOpenUnassignDialog(true);
	}
	const unassignDialogClosed = (unassign) => {
		setOpenUnassignDialog(false)

		if(unassign === true) {
			if(unassignDialogEditConditionOnly) {
				Meteor.call('assets.updateCondition', unassignAsset._id, unassignCondition, unassignConditionDetails, (err, result) => {
					if(err) console.error(err)
					else if(assetIdInput) assetIdInput.focus()
				})
			}
			else {
				// Call assets.unassign(assetId, comment, condition, conditionDetails, date)
				Meteor.call('assets.unassign', foundAsset.assetId, unassignComment, unassignCondition, unassignConditionDetails, (err, result) => {
					if (err) console.error(err)
					else if (assetIdInput) assetIdInput.focus()
				})
			}
		}
	}

	return (
		<>
			<Dialog open={openUnassignDialog} onClose={unassignDialogClosed}>
				<DialogTitle>{unassignDialogEditConditionOnly ? "Edit Condition" : "Unassign Asset"}</DialogTitle>
				<DialogContent style={{display: 'flex', flexDirection: 'column'}}>
					<div>
						<TextField style={cssEditorField} select variant="standard" label="Condition" value={unassignCondition} onChange={(e)=>{setUnassignCondition(e.target.value)}}>
							{conditions.map((condition, i) => {
								return <MenuItem key={i} value={condition}>{condition}</MenuItem>
							})}
						</TextField>
					</div>
					{!unassignDialogEditConditionOnly && <TextField style={{marginTop: '1rem',minWidth: '30rem'}} variant="standard" label="Comment" value={unassignComment} onChange={(e) => {setUnassignComment(e.target.value)}}/>}
					<TextField style={{marginTop: '1rem',minWidth: '30rem'}} multiline rows={4} variant="outlined" label="Condition Details" value={unassignConditionDetails} onChange={(e) => {setUnassignConditionDetails(e.target.value)}}/>
				</DialogContent>
				<DialogActions>
					<Button onClick={() => unassignDialogClosed(true)}>{unassignDialogEditConditionOnly ? "Save" : "Unassign"}</Button>
					<Button onClick={() => unassignDialogClosed(false)}>Cancel</Button>
				</DialogActions>
			</Dialog>

			<Box style={{marginTop: '1rem',...cssTwoColumnContainer}}>
				<TextField style={cssEditorField} variant="standard" label="Asset ID" inputRef={input=>setAssetIdInput(input)} value={assetId} onChange={(e) => {setAssetId(e.target.value.toUpperCase())}}/>
			</Box>
			{foundAsset && (
				<div>
					<div>Serial: {foundAsset.serial}</div>
					<div>Condition: {foundAsset.condition}</div>
					<div>Condition Details: {foundAsset.conditionDetails}</div>
					{foundAsset.assignee && (
						<>
							<div>Assigned on: {foundAsset.assignmentDate.toString()}</div>
							<div>Assigned to: {foundAsset.assignee.firstName} {foundAsset.assignee.lastName} {foundAsset.assignee.grade && foundAsset.assignee.grade} (<Link to={"/search?email=" + encodeURIComponent(foundAsset.assignee.email)}>{foundAsset.assignee.email}</Link>)</div>
							<Button variant="contained" color='secondary' className="button" onClick={()=>unassign(false)}>Unassign</Button>
							{"  "}
							<Button variant="contained" color='secondary' className="button" onClick={()=>unassign(true)}>Edit</Button>
						</>
					)}
				</div>
			)}
		</>
	)
}

export default () => {
	Meteor.subscribe('students');
	Meteor.subscribe('staff');
	Meteor.subscribe('assetTypes');
	Meteor.subscribe('assets');

	return (
		<AssignmentsByAsset/>
	)
}