import { Light, Logout, Asleep } from "@carbon/icons-react";
import { TextUtil } from "@greatness/util";
import { useCallback } from "react";

import { useSessionContext } from "@/components/SessionContext";
import createUseStyles from "@/theme/createUseStyles";
import { cn } from "@/util/cn";
import { useDarkMode } from "@/util/useDarkMode";

const useStyles = createUseStyles(({ sizes, media }) => ({
  closeButton: {
    border: "none",
    height: 64,
    marginLeft: "auto",
  },
  themeButton: {
    border: "none",
    height: 64,
  },
  pageHeader: {
    margin: "0 auto",
    maxWidth: sizes.maxWidthValue,
    [media.md]: {
      alignItems: "center",
      padding: "var(--spacing-m) var(--spacing-l)",
    },
  },
  titleWrapper: {
    [media.md]: {
      alignItems: "center",
      flex: 1,
      flexFlow: "row",
      gap: "var(--spacing-m)",
    },
  },
}));

export default function PageHeader({
  className,
  title,
}: {
  className?: string;
  title?: string;
}) {
  const classes = useStyles();
  const { isAuthenticated, logout } = useSessionContext();
  const { isDarkMode, toggleDarkMode } = useDarkMode();

  const handleClose = useCallback(
    () => (isAuthenticated ? logout() : window.close()),
    [isAuthenticated, logout],
  );

  return (
    <div className={cn(classes.pageHeaderWrapper)}>
      <div className={cn("flex pt-xxl pr-m pb-0 pl-m", classes.pageHeader, className)}>
        <div className={cn("flex flex-col", classes.titleWrapper)}>
          {!TextUtil.isEmpty(title) && (
            <h2 className="font-size-l flex-1 m-0">{title!}</h2>
          )}
        </div>

        <button
          type="button"
          className={cn("items-center justify-center flex flex-col p-l cursor-pointer", classes.themeButton)}
          onClick={toggleDarkMode}
          title={isDarkMode ? "Switch to light mode" : "Switch to dark mode"}
          style={{ background: "var(--body-bg)", color: "var(--body-text)" }}
        >
          {isDarkMode ? <Light size={24} /> : <Asleep size={24} />}
        </button>

        <button
          type="button"
          className={cn("items-center justify-center flex flex-col p-l cursor-pointer", classes.closeButton)}
          onClick={handleClose}
          style={{ background: "var(--body-bg)", color: "var(--body-text)" }}
        >
          <Logout />
        </button>
      </div>
    </div>
  );
};
