"use client";

import { ColorModeContext } from "@contexts/color-mode";
import DarkModeOutlined from "@mui/icons-material/DarkModeOutlined";
import LightModeOutlined from "@mui/icons-material/LightModeOutlined";
import { IoChatbubbleEllipsesOutline } from "react-icons/io5";
import Logout from "@mui/icons-material/Logout";
import SwapHoriz from "@mui/icons-material/SwapHoriz";
import ChatOutlined from "@mui/icons-material/ChatOutlined";
import AppBar from "@mui/material/AppBar";
import Avatar from "@mui/material/Avatar";
import ButtonBase from "@mui/material/ButtonBase";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import { useGetIdentity, useLogout } from "@refinedev/core";
import { HamburgerMenu, RefineThemedLayoutHeaderProps } from "@refinedev/mui";
import React, { useContext, useState } from "react";
import { ProjectSelector } from "@components/project/ProjectSelector";
import { GlobalChatbox } from "@components/chat/GlobalChatbox";
import { setMapExtent, setMapWorkspace, setNetworkName } from "@config/config";
import { useProjectStore } from "@/store/projectStore";

type IUser = {
  id?: string;
  name?: string;
  avatar?: string;
};

export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
  sticky = true,
}) => {
  const { mode, setMode } = useContext(ColorModeContext);
  const { mutate: logout } = useLogout();
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [showProjectSelector, setShowProjectSelector] = useState(false);
  const [showChatbox, setShowChatbox] = useState(false);
  const open = Boolean(anchorEl);
  const setCurrentProjectId = useProjectStore(
    (state) => state.setCurrentProjectId,
  );

  const { data: user } = useGetIdentity<IUser>();

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

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const handleSwitchProjectClick = () => {
    handleMenuClose();
    setShowProjectSelector(true);
  };

  const handleProjectSelect = (
    projectId: string,
    workspace: string,
    networkName: string,
    extent: number[],
  ) => {
    setMapWorkspace(workspace);
    setNetworkName(networkName);
    setMapExtent(extent);
    localStorage.setItem("NEXT_PUBLIC_MAP_WORKSPACE", workspace);
    localStorage.setItem("NEXT_PUBLIC_NETWORK_NAME", networkName);
    localStorage.setItem("NEXT_PUBLIC_MAP_EXTENT", extent.join(","));
    localStorage.removeItem(`${workspace}_map_view`);
    setCurrentProjectId(projectId || networkName || workspace);
    setShowProjectSelector(false);
    window.location.reload();
  };

  return (
    <AppBar position={sticky ? "sticky" : "relative"}>
      <Toolbar>
        <Stack
          direction="row"
          width="100%"
          justifyContent="flex-end"
          alignItems="center"
        >
          <HamburgerMenu />
          <Stack
            direction="row"
            width="100%"
            justifyContent="flex-end"
            alignItems="center"
          >
            {/* <IconButton
              color="inherit"
              onClick={() => {
                setMode();
              }}
            >
              {mode === "dark" ? <LightModeOutlined /> : <DarkModeOutlined />}
            </IconButton> */}

            {(user?.avatar || user?.name) && (
              <>
                <IconButton
                  color="inherit"
                  onClick={() => setShowChatbox(true)}
                  sx={{ mr: 1 }}
                >
                  <IoChatbubbleEllipsesOutline />
                </IconButton>
                <ButtonBase
                  onClick={handleMenuOpen}
                  sx={{
                    borderRadius: "30px",
                    padding: "6px 12px",
                    marginLeft: "8px",
                    transition: "all 0.3s ease",
                    border: "1px solid transparent",
                    "&:hover": {
                      backgroundColor:
                        mode === "dark"
                          ? "rgba(255, 255, 255, 0.05)"
                          : "rgba(0, 0, 0, 0.04)",
                      transform: "translateY(-1px)",
                      border: `1px solid ${mode === "dark"
                          ? "rgba(255, 255, 255, 0.2)"
                          : "rgba(0, 0, 0, 0.1)"
                        }`,
                      boxShadow:
                        mode === "dark"
                          ? "0 4px 12px rgba(0,0,0,0.3)"
                          : "0 4px 12px rgba(0,0,0,0.08)",
                    },
                    "&:active": {
                      transform: "translateY(0px)",
                      boxShadow: "none",
                    },
                  }}
                >
                  <Stack
                    direction="row"
                    gap="12px"
                    alignItems="center"
                    justifyContent="center"
                  >
                    {user?.name && (
                      <Typography
                        sx={{
                          display: {
                            xs: "none",
                            sm: "inline-block",
                          },
                          fontWeight: 500,
                        }}
                        variant="subtitle2"
                      >
                        {user?.name}
                      </Typography>
                    )}
                    <Avatar
                      src={user?.avatar}
                      alt={user?.name}
                      sx={{
                        width: 32,
                        height: 32,
                        border: `2px solid ${mode === "dark"
                            ? "rgba(255,255,255,0.2)"
                            : "rgba(0,0,0,0.1)"
                          }`,
                        transition: "transform 0.3s ease",
                        ".MuiButtonBase-root:hover &": {
                          transform: "rotate(5deg) scale(1.05)",
                          borderColor: "primary.main",
                        },
                      }}
                    />
                  </Stack>
                </ButtonBase>
                <Menu
                  anchorEl={anchorEl}
                  open={open}
                  onClose={handleMenuClose}
                  transformOrigin={{ horizontal: "right", vertical: "top" }}
                  anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
                  PaperProps={{
                    sx: {
                      borderRadius: 2,
                      minWidth: 180,
                      marginTop: "8px",
                      background:
                        mode === "dark"
                          ? "rgba(30, 30, 30, 0.95)"
                          : "rgba(255, 255, 255, 0.95)",
                      backdropFilter: "blur(10px)",
                      boxShadow:
                        mode === "dark"
                          ? "0px 4px 20px rgba(0, 0, 0, 0.5)"
                          : "0px 4px 20px rgba(0, 0, 0, 0.1)",
                    },
                  }}
                >
                  <MenuItem onClick={handleSwitchProjectClick}>
                    <ListItemIcon>
                      <SwapHoriz fontSize="small" />
                    </ListItemIcon>
                    <ListItemText>切换项目</ListItemText>
                  </MenuItem>
                  <Divider />
                  <MenuItem onClick={() => logout()}>
                    <ListItemIcon>
                      <Logout fontSize="small" />
                    </ListItemIcon>
                    <ListItemText>登出</ListItemText>
                  </MenuItem>
                </Menu>
                <ProjectSelector
                  open={showProjectSelector}
                  onSelect={handleProjectSelect}
                  onClose={() => setShowProjectSelector(false)}
                />
              </>
            )}
            <GlobalChatbox
              open={showChatbox}
              onClose={() => setShowChatbox(false)}
            />
          </Stack>
        </Stack>
      </Toolbar>
    </AppBar>
  );
};
