"use client";

import {
  useState,
  type MouseEvent,
} from "react";

import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip";
import { useTheme } from "@mui/material/styles";

import { dashboardAssets } from "@/components/dashboard/dashboard-assets";
import { MenuBarsIcon } from "@/components/dashboard/dashboard-icons";
import { useAppTheme } from "@/components/providers/app-theme-provider";
import { useCurrentUser } from "@/features/auth/hook/use-current-user";
import { useSystemNotifications } from "@/features/system-notifications/use-system-notifications";

import { HeaderActionIcon } from "./header-action-icon";
import { HeaderSearch } from "./header-search";
import { LanguageSwitcher } from "./language-switcher";
import { NotificationDropdown } from "./notification-dropdown";
import { ProfileDropdown } from "./profile-dropdown";
import { UserProfileButton } from "./user-profile-button";

type HeaderProps = {
  onMenuClick: () => void;
};

export function Header({
  onMenuClick,
}: HeaderProps) {
  const theme = useTheme();

  const { toggleMode } = useAppTheme();

  const {
    user,
    isLoading,
  } = useCurrentUser();

  const {
    unreadCount,
    systemNotificationEnabled,
    unreadBadgeEnabled,
    settingLoading,
  } = useSystemNotifications();

  const [profileAnchor, setProfileAnchor] =
    useState<HTMLElement | null>(null);

  const [
    notificationAnchor,
    setNotificationAnchor,
  ] = useState<HTMLElement | null>(null);

  function openProfileMenu(
    event: MouseEvent<HTMLElement>,
  ) {
    setNotificationAnchor(null);
    setProfileAnchor(event.currentTarget);
  }

  function closeProfileMenu() {
    setProfileAnchor(null);
  }

  function openNotificationMenu(
    event: MouseEvent<HTMLElement>,
  ) {
    setProfileAnchor(null);

    /*
     * System Notification បិទ
     * មិនអនុញ្ញាតឱ្យបើក dropdown។
     */
    if (
      settingLoading ||
      !systemNotificationEnabled
    ) {
      setNotificationAnchor(null);
      return;
    }

    setNotificationAnchor(
      event.currentTarget,
    );
  }

  function closeNotificationMenu() {
    setNotificationAnchor(null);
  }

  const showUnreadAlert =
    systemNotificationEnabled &&
    unreadBadgeEnabled &&
    unreadCount > 0;

  return (
    <>
      <Box
        sx={{
          position: "sticky",
          top: 0,
          zIndex: 1000,
          minHeight: 64,
          px: {
            xs: 2,
            sm: 3,
            lg: 3.5,
          },
          py: 1.25,
          bgcolor:
            theme.palette.background.paper,
          borderBottom: `1px solid ${theme.palette.divider}`,
          display: "grid",
          gridTemplateColumns: {
            xs: "auto 1fr",
            sm: "1fr auto auto",
            lg: "1fr auto auto",
          },
          alignItems: "center",
          columnGap: {
            xs: 1.5,
            sm: 2,
            lg: 4,
          },
          rowGap: 1,
        }}
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: {
              xs: "flex-start",
              sm: "flex-end",
            },
            minWidth: 0,
          }}
        >
          <IconButton
            onClick={onMenuClick}
            sx={{
              display: {
                xs: "inline-flex",
                lg: "none",
              },
              color:
                theme.palette.text.secondary,
              borderRadius: "8px",
            }}
          >
            <MenuBarsIcon />
          </IconButton>
        </Box>

        <Box
          sx={{
            display: "flex",
            justifyContent: {
              xs: "flex-end",
              sm: "center",
            },
            gridColumn: {
              xs: "2 / 3",
              sm: "2 / 3",
            },
            minWidth: 0,
          }}
        >
          <HeaderSearch />
        </Box>

        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-end",
            gap: {
              xs: 1,
              sm: 2.25,
            },
            gridColumn: {
              xs: "1 / -1",
              sm: "3 / 4",
            },
            width: {
              xs: "100%",
              sm: "auto",
            },
          }}
        >
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 2.25,
            }}
          >
            <LanguageSwitcher />

            <HeaderActionIcon
              src={
                dashboardAssets.topbarMoon
              }
              onClick={toggleMode}
            />

            <Tooltip
              title={
                systemNotificationEnabled
                  ? "Notifications"
                  : "System notifications are disabled"
              }
              arrow
            >
              <Box
                component="span"
                sx={{
                  display: "inline-flex",
                  opacity:
                    settingLoading ||
                    !systemNotificationEnabled
                      ? 0.45
                      : 1,
                  cursor:
                    systemNotificationEnabled
                      ? "pointer"
                      : "not-allowed",
                }}
              >
                <HeaderActionIcon
                  src={
                    dashboardAssets.topbarBell
                  }
                  showAlert={showUnreadAlert}
                  onClick={
                    openNotificationMenu
                  }
                />
              </Box>
            </Tooltip>
          </Box>

          <UserProfileButton
            open={Boolean(profileAnchor)}
            onClick={openProfileMenu}
            name={user?.name ?? null}
            position={
              user?.position ?? null
            }
            avatar={user?.avatar ?? null}
            isLoading={isLoading}
          />
        </Box>
      </Box>

      <ProfileDropdown
        anchorEl={profileAnchor}
        open={Boolean(profileAnchor)}
        onClose={closeProfileMenu}
      />

      <NotificationDropdown
        anchorEl={notificationAnchor}
        open={
          Boolean(notificationAnchor) &&
          systemNotificationEnabled
        }
        onClose={closeNotificationMenu}
      />
    </>
  );
}