import { Meteor } from 'meteor/meteor';
import React, { useState, useEffect, lazy, Suspense } from 'react';
import { useTracker } from 'meteor/react-meteor-data';
import _ from 'lodash';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import {Route, Routes, useNavigate} from "react-router-dom";

//Example Tabs:
// let tabs = [
// 	{
// 		title: "Asset List",
// 		getElement: () => {
// 			const AssetList = lazy(()=>import('./Assets/AssetList'))
// 			return <AssetList/>
// 		},
// 		path: '/assetList',
// 		href: 'assetList'
// 	},
// 	{
// 		title: "Add Assets",
// 		getElement: () => {
// 			const AddAssets = lazy(()=>import('./Assets/AddAssets'))
// 			return <AddAssets/>
// 		},
// 		path: '/addAssets',
// 		href: 'addAssets'
// 	},
// ]

const LinkTab = (props) => {
	let nav = useNavigate()
	return <Tab component='a' onClick={(e) => {
		e.preventDefault()
		nav(props.href)
	}} {...props}/>
}

export default ({tabs}) => {
	let pathName = location.pathname;
	let initialTab = tabs.findIndex(tab => {return pathName.endsWith(tab.path)})
	let defaultTabPath = tabs[0].path.slice(0, tabs[0].path.lastIndexOf('/'))
	
	if(initialTab === -1) {
		initialTab = 0
	}
	
	const [value, setValue] = useState(initialTab)

	const valueChanged = (e, newValue) => {
		setValue(newValue)
	}
	// console.log(defaultTabPath)
	return (
		<>
			<Box sx={{width: '100%'}}>
				<Tabs value={value} onChange={valueChanged} aria-label='nav tabs'>
					{tabs.map((tab, i) => {return (
						<LinkTab key={i} label={tab.title} href={tab.href}/>
					)})}
				</Tabs>
			</Box>
			<Suspense fallback={<div/>}>
				<Routes>
					<Route path={defaultTabPath} element={tabs[0].getElement()}/>
					{tabs.map((tab, i) => {return (
						<Route key={i} path={tab.path} element={tab.getElement()}/>
					)})}
				</Routes>
			</Suspense>
		</>
	)
}