import AdbIcon from '@mui/icons-material/Adb';
import MenuIcon from '@mui/icons-material/Menu';
import SearchIcon from '@mui/icons-material/Search';
import { Autocomplete, TextField } from '@mui/material';
import AppBar from '@mui/material/AppBar';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Toolbar from '@mui/material/Toolbar';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import { useQuery } from '@tanstack/react-query';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import Item from '../../components/Item';
import ThemeToggle from '../../theme/ThemeToggle';
import { useAccount } from '../AccountProvider';
import { fetchItemList } from '../query/Queries';
import LoginDialog from './LoginDialog';
import './NavBar.css';

export default function NavBar() {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(null);
    const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);

    const { user, logout } = useAccount();

    const [loginOpen, setLoginOpen] = React.useState(false);
    const [loginData, setLoginData] = React.useState({ password: '', email: '', customerId: 0 });


    const [itemNames, setItemNames] = React.useState<string[]>([]); // Für Autocomplete

    const pageKeys = ['components', 'checkout', 'contact', 'admin'];

    const pages = pageKeys.map(key => ({ key, label: t(key) }));
    const settings = user
        ? [
            { key: 'account', label: t('account') },
            { key: 'orders', label: t('orders') },
            { key: 'logout', label: t('logout') }
        ]
        : [
            { key: 'login', label: t('login') }
        ];

    const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorElNav(event.currentTarget);
    };

    const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorElUser(event.currentTarget);
    };

    const handleCloseNavMenu = (link: string) => {
        setAnchorElNav(null);
        navigate(`/${link.toLowerCase()}`);
    };

    const handleCloseUserMenu = (link: string) => {
        setAnchorElUser(null);
        if (link === 'login') {
            setLoginOpen(true);
        } else if (link === 'logout') {
            logout();
            if (
                location.pathname.startsWith('/account') ||
                location.pathname.startsWith('/orders')
            ) {
                navigate('/');
            }
        } else {
            navigate(`/${link.toLowerCase()}`)
        }
    };

    const handleLoginSubmit = () => {
        setLoginOpen(false);
    };


    // useQuery, um die Item-Namen zu laden
    const { data: items = [] } = useQuery<Item[]>({
        queryKey: ["fetchItemList"],
        queryFn: fetchItemList,
    });

    React.useEffect(() => {
        // Extrahiere die Namen der Items für Autocomplete
        setItemNames(items.map((item) => item.name));
    }, [items]);

    const handleSearch = (_: React.SyntheticEvent, value: string | null) => {

        if (!value) {
            // Wenn der Suchwert leer ist, navigiere zur Homepage ohne Suchparameter
            navigate("/");
        } else {
            // Navigiere zur Homepage mit dem Suchparameter
            navigate(`/?search=${encodeURIComponent(value)}`);
        }
    };

    return (
        <>
            <AppBar className="navbar" color="primary" elevation={4}>
                <Toolbar
                    disableGutters
                    sx={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        px: 3
                    }}
                >
                    <Box sx={{ display: "flex", alignItems: "center", minWidth: "0px" }}>
                        <AdbIcon className='navbar-logo' />
                        <Typography
                            variant="h6"
                            noWrap
                            component="a"
                            href="/"
                            sx={{
                                fontFamily: "monospace",
                                fontWeight: 700,
                                letterSpacing: ".3rem",
                                color: "white",
                                textDecoration: "none",
                                ml: 1,
                            }}
                        >
                            Digitaler Produktionsshop
                        </Typography>
                    </Box>

                    <Box sx={{ flexGrow: 1, display: "flex", justifyContent: "center", px: 3 }}>
                        <Autocomplete
                            sx={{ flexGrow: 1, minWidth: "150px", maxWidth: "600px" }}
                            freeSolo
                            options={itemNames} // Item-Namen für Autocomplete
                            onInputChange={handleSearch} // Suche auslösen
                            renderInput={(params) => (
                                <TextField
                                    {...params}
                                    placeholder={t("search") + "..."}
                                    InputProps={{
                                        ...params.InputProps,
                                        startAdornment: (
                                            <SearchIcon sx={{ color: "white", mr: 1 }} />
                                        ),
                                    }}
                                    sx={{
                                        '& .MuiOutlinedInput-root': {
                                            '& fieldset': {
                                                borderColor: 'white',
                                                borderWidth: '1px',
                                            },
                                            '&:hover fieldset': {
                                                borderColor: 'white',
                                            },
                                            '&.Mui-focused fieldset': {
                                                borderColor: 'white',
                                            },
                                        },
                                        input: {
                                            color: 'white',
                                        },
                                    }}
                                />
                            )}
                        />
                    </Box>

                    <Box sx={{ display: "flex", alignItems: "center", gap: 2, marginLeft: 'auto' }}>
                        <Box sx={{ display: { xs: "none", md: "flex" }, gap: 2 }}>
                            {pages.map(({ key, label }) => (
                                <Button
                                    key={key}
                                    onClick={() => handleCloseNavMenu(key)}
                                    sx={{ color: "white", fontWeight: 500 }}
                                >
                                    {label}
                                </Button>
                            ))}
                        </Box>

                        <Box sx={{ display: { xs: "flex", md: "none" } }}>
                            <IconButton
                                size="large"
                                aria-label="menu"
                                onClick={handleOpenNavMenu}
                                color="inherit"
                            >
                                <MenuIcon />
                            </IconButton>
                            <Menu
                                anchorEl={anchorElNav}
                                anchorOrigin={{ vertical: "top", horizontal: "right" }}
                                transformOrigin={{ vertical: "top", horizontal: "right" }}
                                open={Boolean(anchorElNav)}
                                onClose={() => setAnchorElNav(null)}
                            >
                                {pages.map(({ key, label }) => (
                                    <MenuItem key={key} onClick={() => handleCloseNavMenu(key)}>
                                        <Typography>{label}</Typography>
                                    </MenuItem>
                                ))}
                            </Menu>
                        </Box>

                        <ThemeToggle />
                        <Tooltip title={t('openSettings')} placement='bottom-end'>
                            <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
                                <Avatar alt="Florian Speicher" src="/static/images/avatar/2.jpg" />
                            </IconButton>
                        </Tooltip>
                        <Menu
                            sx={{ mt: "15px" }}
                            id="menu-appbar-user"
                            anchorEl={anchorElUser}
                            open={Boolean(anchorElUser)}
                            onClose={() => setAnchorElUser(null)}
                        >
                            {settings.map(({ key, label }) => (
                                <MenuItem key={key} onClick={() => handleCloseUserMenu(key)}>
                                    <Typography sx={{ textAlign: "center" }}>{label}</Typography>
                                </MenuItem>
                            ))}
                        </Menu>
                    </Box>
                </Toolbar>
            </AppBar>
            <LoginDialog
                open={loginOpen}
                onClose={() => setLoginOpen(false)}
                onSubmit={handleLoginSubmit}
                loginData={loginData}
                setLoginData={setLoginData}
            />
            <div className="navbar-offset" />
        </>
    );
}
