import {Meteor} from "meteor/meteor";
import React from "react";
import {useTheme} from "@mui/material/styles";
import {useTracker} from "meteor/react-meteor-data";
import {AssetTypes} from "/imports/api/asset-types";
import {Assets} from "/imports/api/assets";
import {Students} from "/imports/api/students";
import {Staff} from "/imports/api/staff";
import SimpleTable from "/imports/ui/util/SimpleTable";
import moment from "moment";
import {Box, Grid} from "@mui/material";
import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";
import Button from "@mui/material/Button";

const AssignmentsReport = () => {
	const theme = useTheme();

	const {people} = useTracker(async () => {
		let assets = await Assets.find({assigneeId: {$exists: true}, assigneeType: "Student"}).fetchAsync()
		let assetTypes = await AssetTypes.find().fetchAsync()
		let students = await Students.find().fetchAsync()
		let people = []

		let assetTypesById = assetTypes.reduce((map, obj) => {map[obj._id] = obj; return map}, {})
		let studentsById = students.reduce((map, obj) => {map[obj._id] = obj; return map}, {})
		// let staffById = staff.reduce((map, obj) => {map[obj._id] = obj; return map}, {})

		for(let next of assets) {
			let student = studentsById[next.assigneeId]
			let assetType = assetTypesById[next.assetTypeId]
			
			people.push({_id: next._id, firstName: student.firstName, lastName: student.lastName, grade: student.grade, assetName: assetType.name, checkOutDate: next.assignmentDate, condition: next.condition, assetTag: next.assetId})
		}
		
		people.sort((a, b) => {
			let firstName = a.firstName.localeCompare(b.firstName)
			let lastName = a.lastName.localeCompare(b.lastName)
			
			return a.grade === b.grade ? lastName ? lastName : firstName : b.grade - a.grade
		})
		
		return {people}
	});
	
	const exportData = () => {
		let csv
		
		for(let next of people) {
			if(csv) csv += "\r\n"
			else csv = "First Name;Last Name;Grade;Asset Name;Check Out Date;Condition;Asset Tag\r\n"
			
			csv += next.firstName + ";" + next.lastName + ";" + next.grade + ";" + next.assetName + ";" + next.checkOutDate + ";" + next.condition + ";" + next.assetTag + ";"
		}
		
		let blob = new Blob([csv], {type: 'text/csv'})
		let a = document.createElement('a')
		a.download = 'export.csv'
		a.href = window.URL.createObjectURL(blob)
		a.click()
	}

	// const {checkedOutAssets} = useTracker(() => {
	// 	let assets = Assets.find({assigneeId: {$exists: true}}).fetch()
	// 	let assetTypes = AssetTypes.find().fetch()
	// 	let students = Students.find().fetch()
	// 	let staff = Staff.find().fetch()
	//	
	// 	let assetTypesById = assetTypes.reduce((map, obj) => {map[obj._id] = obj; return map}, {})
	// 	let studentsById = students.reduce((map, obj) => {map[obj._id] = obj; return map}, {})
	// 	let staffById = staff.reduce((map, obj) => {map[obj._id] = obj; return map}, {})
	//	
	// 	for(let next of assets) {
	// 		next.assetType = assetTypesById[next.assetTypeId]
	// 		if(next.assigneeType === "Staff")
	// 			next.person = staffById[next.assigneeId]
	// 		else
	// 			next.person = studentsById[next.assigneeId]
	// 	}
	//
	// 	let checkedOutAssets = [];
	//
	// 	for(let next of assets) {
	// 		if(next.assigneeType === "Student") {
	// 			checkedOutAssets.push(next);
	// 		}
	// 	}
	//
	// 	return {checkedOutAssets}
	// });

	// people.push({firstName: student.firstName, lastName: student.lastName, grade: student.grade, assetName: assetType.name, checkOutDate: next.assignmentDate, condition: next.condition, assetTag: next.assetTag})
	const columns = [
		{
			name: "First Name",
			//value: (checkedOutAsset) => checkedOutAsset.person ? checkedOutAsset.person.firstName : ""
			value: (next) => next.firstName
		},
		{
			name: "Last Name",
			// value: (checkedOutAsset) => checkedOutAsset.person ? checkedOutAsset.person.lastName : ""
			value: (next) => next.lastName
		},
		{
			name: "Grade",
			value: (next) => next.grade,
		},
		{
			name: "Asset",
			value: (next) => next.assetName,
		},
		{
			name: "Asset Tag",
			value: (next) => next.assetTag,
		},
		{
			name: "Checkout Date",
			value: (next) => moment(next.assignmentDate).format("YYYY-MM-DD"),
		},
		{
			name: "Condition",
			value: (next) => next.condition,
		},
	]

	const options = {
		key: (row) => row._id,
		// editor: (row, close) => {return (<AssetTypeEditor value={row} close={close}/>)},
		add: false,
		maxHeight: '40rem',
		keyHandler: (e, selected) => {
			// if(selected && selected._id && e.key === "Delete") {
			// 	Meteor.call("assetTypes.remove", selected._id);
			// }
		}
	}
	
	return (
		<>
			
			<Box component="div" sx={{m: 2, p: 2, border: '1px dashed grey'}}>
				<Button variant="contained" color='secondary' className="button" onClick={()=>exportData()}>Export</Button>
			{/*	<h4 style={{margin: 0, padding: 0}}>Filter</h4>*/}
			{/*	<Grid container spacing={2}>*/}
			{/*		<Grid item xs={4}>*/}
			{/*			<TextField style={cssEditorField} select variant="standard" value={assetTypeId} onChange={(e)=>{setAssetTypeId(e.target.value)}} label="Grade">*/}
			{/*				{assetTypes.map((assetType, i) => {*/}
			{/*					return <MenuItem key={i} value={assetType._id}>{assetType.name}</MenuItem>*/}
			{/*				})}*/}
			{/*			</TextField>*/}
			{/*		</Grid>*/}
			{/*	</Grid>*/}
			</Box>
			<SimpleTable rows={people} columns={columns} options={options}/>
		</>
	)
}

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

	return (
		<AssignmentsReport/>
	)
}