import React, { useState } from 'react';
import { AppBar as MuiAppBar, Box, Tab as MuiTab, Tabs, IconButton } from '@material-ui/core';
import CloseIcon from '@material-ui/icons/Close';
import AddIcon from '@material-ui/icons/Add';
import AddTabMenu, { NewTabProps } from './AddTabMenu';

export interface IProps {
    tabLabels: string[],
    selectedTab: number,
    setSelectedTab: (n: number) => void,
    onCloseTab: (idx: number) => void,
    onAddTab: (w: NewTabProps) => void,
}

export interface TabProps {
    onClose: () => void,
}

export function Tab(props: any) {
    const { onClose, label, ...restProps } = props;

    const labelElem = <Box
        display="flex"
        alignItems="center"
        justifyContent="center"
    >
        {label}
        <Box ml={1}>
            <IconButton
                size="small"
                color="inherit"
                onClick={onClose}
            >
                <CloseIcon />
            </IconButton>
        </Box>
    </Box>;

    return <MuiTab
        label={labelElem}
        {...restProps}
    />
}

export default function AppBar(props: IProps) {
    const [addMenuAnchorEl, setAddMenuAnchorEl] = React.useState<null | HTMLElement>(null);

    const onOpenAddMenu = (event: any) => {
        setAddMenuAnchorEl(event.currentTarget);
    };
    const onCloseAddMenu = () => {
        setAddMenuAnchorEl(null);
    };
    const onAddTab = (w: NewTabProps) => {
        props.onAddTab(w);
    };

    return <>
        <MuiAppBar position="static" style={{ background: 'grey' }}>
            <Box display="flex" alignItems="center">
                <Box m={0.5} display="flex" alignItems="center">
                    <img height="30px" src={process.env.PUBLIC_URL + "/logo.svg"} alt="error"></img>
                </Box>
                <Tabs value={props.selectedTab} onChange={(e: any, v: number) => props.setSelectedTab(v)}>
                    {props.tabLabels.map((l: string, idx: number) => <Tab
                        label={l}
                        value={idx}
                        onClose={() => props.onCloseTab(idx)}
                    />)}
                </Tabs>
                <IconButton color="inherit" onClick={onOpenAddMenu}><AddIcon /></IconButton>
            </Box>
        </MuiAppBar>
        <AddTabMenu
            anchorEl={addMenuAnchorEl}
            onClose={onCloseAddMenu}
            onCreateTab={onAddTab}
        />
    </>
}