import React from 'react';
import { useState, useEffect, useRef } from 'react';
import { useMediaQuery } from 'react-responsive';
import useResize from '../hooks/resizeHook';

import { Player, Team } from '../types';
import { positionMap } from '../positionMap';

import AppBar from '@mui/material/AppBar';
import Container from '@mui/material/Container';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import SearchIcon from '@mui/icons-material/Search';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import { Button } from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import HomeIcon from '@mui/icons-material/Home';
import ClickAwayListener from '@mui/material/ClickAwayListener';
import Grow from '@mui/material/Grow';
import Paper from '@mui/material/Paper';
import Popper from '@mui/material/Popper';
import MenuItem from '@mui/material/MenuItem';
import MenuList from '@mui/material/MenuList';

export default function NavBar() {
    const isMobile = useMediaQuery({ maxWidth: 600 });
    useResize();

    const [players, setPlayers] = useState<Player[]>([]);
    const [searchFirstName, setSearchFirstName] = useState("");
    const [searchLastName, setSearchLastName] = useState("");

    // TEAMS menu variables
    const [teams, setTeams] = useState<Team[]>([]);
    const [openTeamsMenu, setOpenTeamsMenu] = useState(false);
    const anchorRef = useRef<HTMLButtonElement>(null);

    async function fetchPlayersByName(firstname: string, lastname: string) {
        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_API_URL}/player/search/${firstname}-${lastname}`);
            const data = await response.json();
            setPlayers(data);
        } catch (error) {
            console.error('Error searching for player: ', error);
        }
    }

    useEffect(() => {
        // eslint-disable-next-line react-hooks/set-state-in-effect
        if (searchFirstName.length > 0) {
            fetchPlayersByName(searchFirstName, searchLastName == " " ? "" : searchLastName);
        }
    }, [searchFirstName, searchLastName]);

    const handleTeamsMenuToggle = () => {
        setOpenTeamsMenu((teamsMenuPrevOpen) => !teamsMenuPrevOpen);
    };

    // TEAMS menu functions
    async function fetchTeams() {
        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_API_URL}/teams`);
            const data = await response.json();
            setTeams(data);
        } catch (error) {
            console.error('Error fetching teams: ', error);
        }
    }

    useEffect(() => {
        // eslint-disable-next-line react-hooks/set-state-in-effect
        fetchTeams();
    }, [])

    const handleTeamsMenuClose = (event: Event | React.SyntheticEvent) => {
        if (
            anchorRef.current &&
            anchorRef.current.contains(event.target as HTMLElement)
        ) {
            return;
        }

        setOpenTeamsMenu(false);
    };

    function handleListKeyDown(event: React.KeyboardEvent) {
        if (event.key === 'Tab') {
            event.preventDefault();
            setOpenTeamsMenu(false);
        } else if (event.key === 'Escape') {
            setOpenTeamsMenu(false);
        }
    }

    // return focus to the button when we transitioned from !open -> open
    const teamsMenuPrevOpen = React.useRef(openTeamsMenu);
    React.useEffect(() => {
        if (teamsMenuPrevOpen.current === true && openTeamsMenu === false) {
            anchorRef.current!.focus();
        }

        teamsMenuPrevOpen.current = openTeamsMenu;
    }, [openTeamsMenu]);

    function renderTeamsMenuItems() {
        return teams.map((team, index) => {
            return (
                <a href={`/teams/${team.teamid}`} key={index}>
                    <MenuItem onClick={handleTeamsMenuClose} key={index}>
                        {team.name}
                    </MenuItem >
                </a>
            )
        });
    }

    return (
        <AppBar position="fixed" sx={{ bgcolor: "#003087", placeContent: "center" }} className="flex">
            <Container maxWidth={"xl"}>
                <Toolbar disableGutters>
                    {isMobile ?
                        <a href="/">
                            <HomeIcon />
                        </a>
                        :
                        <Typography
                            variant="h6"
                            noWrap
                            component="a"
                            href="/"
                        >
                            <HomeIcon style={{ marginBottom: 5 }} />&nbsp;
                            HOME
                        </Typography>
                    }
                    <Divider
                        orientation="vertical"
                        flexItem
                        variant="middle"
                        style={{ borderColor: "white", marginLeft: 15, marginRight: 15 }}
                    />
                    <SearchIcon />
                    <Autocomplete
                        sx={{
                            width: 300,
                            bgcolor: "white",
                            borderRadius: 2
                        }}
                        freeSolo
                        id="player-searchbar"
                        options={players.map((player) => {
                            return `${player.firstname} ${player.lastname}`;
                        })}
                        onInputChange={(event, value) => {
                            const splitSearchBySpace = value?.toString().split(" ");
                            setSearchFirstName(splitSearchBySpace[0]);
                            setSearchLastName(splitSearchBySpace[1]);
                        }}
                        renderInput={(params) => {
                            return (
                                <TextField
                                    {...params}
                                    label="Search Players by First Name"
                                    slotProps={{
                                        input: {
                                            ...params.InputProps,
                                            type: 'search'
                                        }
                                    }}
                                />
                            )
                        }}
                        renderOption={(props, option) => {
                            const splitName = option.split(" ");
                            const foundPlayer = players.find((p) => {
                                return p.firstname === splitName[0] && p.lastname === splitName[1];
                            });

                            if (!foundPlayer) return null;
                            
                            return (
                                <li {...props} key={foundPlayer.playerid}>
                                    <div
                                        style={{ cursor: "pointer" }}
                                        onClick={() => {
                                            window.location.href = `/player/${foundPlayer?.playerid}`;
                                        }}
                                    >
                                        {option} #{foundPlayer.number} ({positionMap[foundPlayer.position]})
                                    </div>
                                </li>
                            );
                        }}
                    />
                    <Divider
                        orientation="vertical"
                        flexItem
                        variant="middle"
                        style={{ borderColor: "white", marginLeft: 15, marginRight: 15 }}
                    />
                    <div>
                        <Button
                            ref={anchorRef}
                            id="teams-menu-button"
                            aria-controls={openTeamsMenu ? 'teams-menu-button' : undefined}
                            aria-expanded={openTeamsMenu ? 'true' : undefined}
                            aria-haspopup="true"
                            onClick={handleTeamsMenuToggle}
                            sx={{ color: "white", fontSize: 18 }}
                        >
                            Teams {openTeamsMenu ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
                        </Button>
                        <Popper
                            open={openTeamsMenu}
                            anchorEl={anchorRef.current}
                            role={undefined}
                            placement="bottom-start"
                            transition
                            disablePortal
                        >
                            {({ TransitionProps, placement }) => (
                                <Grow
                                    {...TransitionProps}
                                    style={{
                                        transformOrigin:
                                            placement === 'bottom-start' ? 'left top' : 'left bottom',
                                    }}
                                >
                                    <Paper>
                                        <ClickAwayListener onClickAway={handleTeamsMenuClose}>
                                            <MenuList
                                                autoFocusItem={openTeamsMenu}
                                                id="composition-menu"
                                                aria-labelledby="composition-button"
                                                onKeyDown={handleListKeyDown}
                                                style={{ maxHeight: 500, overflow: 'scroll' }}
                                            >
                                                {renderTeamsMenuItems()}
                                            </MenuList>
                                        </ClickAwayListener>
                                    </Paper>
                                </Grow>
                            )}
                        </Popper>
                    </div>
                </Toolbar>
            </Container>
        </AppBar>
    )
}