import * as React from "react";
import {
  useLocation,
  matchPath
} from "react-router-dom";
import {
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Tooltip,
  Button,
  Box,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import MenuIcon from "@mui/icons-material/Menu";
import LogoutIcon from "@mui/icons-material/Logout";
import DarkModeIcon from "@mui/icons-material/DarkMode";
import LightModeIcon from "@mui/icons-material/LightMode";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../react-auth";
import { ColorModeContext } from "./shared-theme/AppTheme";

interface HeaderProps {
  routerMapping: {
    path: string;
    headerTitle: string;
  }[];
  onDrawerToggle?: () => void;
}

export default function Header({
  routerMapping,
  onDrawerToggle,
}: HeaderProps) {
  const location = useLocation();
  const matchedRoute = routerMapping.find((route) =>
    matchPath({ path: route.path, end: false }, location.pathname)
  );
  const headerTitle = matchedRoute?.headerTitle ?? "Khata";

  const navigate = useNavigate();
  const { currentUser, logout } = useAuth();
  const { mode, toggleColorMode } = React.useContext(ColorModeContext);

  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));

  const isAuthenticated = !!currentUser;

  return (
    <AppBar
      position="fixed"
      color="default"
      sx={{
        zIndex: (theme) => theme.zIndex.drawer + 1,
        backdropFilter: "blur(8px)",
        boxShadow: "none",
        borderBottom: "1px solid",
        borderColor: "divider",
      }}
    >
      <Toolbar>
        {/* MOBILE MENU BUTTON */}
        {isMobile && onDrawerToggle && (
          <IconButton
            color="inherit"
            edge="start"
            onClick={onDrawerToggle}
            sx={{ mr: 2 }}
          >
            <MenuIcon />
          </IconButton>
        )}

        {/* THEME TOGGLE */}
        <IconButton onClick={toggleColorMode} color="inherit" sx={{ mr: 2 }}>
          {mode === 'dark' ? <LightModeIcon /> : <DarkModeIcon />}
        </IconButton>

        {/* TITLE */}
        <Typography
          variant="h6"
          noWrap
          sx={{ fontWeight: "bold", cursor: "pointer" }}
          onClick={() => navigate("/")}
        >
          {headerTitle}
        </Typography>

        <span style={{ flexGrow: 1 }} />

        {/* NAV LINKS */}
        <Box
          sx={{
            display: { xs: "none", md: "flex" },
            alignItems: "center",
            mr: 2,
            gap: 1,
          }}
        >
          {[
            { label: "Fetch", path: "/fetch-requests" },
          ].map(({ label, path }) => (
            <Button
              key={path}
              color="inherit"
              onClick={() => navigate(path)}
              sx={{ textTransform: "none", fontWeight: 500, px: 1.5 }}
              size="small"
            >
              {label}
            </Button>
          ))}
        </Box>

        {/* AUTH SECTION */}
        {isAuthenticated ? (
          <>
            <Box
              sx={{
                display: { xs: "none", sm: "flex" },
                alignItems: "center",
                mr: 2,
              }}
            >
              <Button
                color="inherit"
                onClick={() => navigate("/admin")}
                sx={{ textTransform: "none", fontWeight: 500 }}
              >
                Admin
              </Button>
              <Button
                color="inherit"
                onClick={() => navigate("/profile/me")}
                sx={{ textTransform: "none", fontWeight: 500 }}
              >
                {currentUser.username}
              </Button>
            </Box>

            <Tooltip title="Logout">
              <IconButton color="inherit" onClick={logout}>
                <LogoutIcon />
              </IconButton>
            </Tooltip>
          </>
        ) : (
          <Button
            color="inherit"
            variant="outlined"
            onClick={() => navigate("/login")}
            sx={{ textTransform: "none" }}
          >
            Login
          </Button>
        )}
      </Toolbar>
    </AppBar>
  );
}