import { useGetLocale, useSetLocale, useGetIdentity } from "@refinedev/core";
import {
  Layout as AntdLayout,
  Space,
  Button,
  Dropdown,
  Avatar,
  Typography,
  theme,
  Switch,
} from "antd";
import * as Icons from "@ant-design/icons";
import { useTranslation } from "react-i18next";
import { useContext } from "react";
import { ColorModeContext } from "components/contexts/color-mode";
import type { MenuProps } from "antd";

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

const { DownOutlined } = Icons;
const { Text } = Typography;
const { useToken } = theme;

export const Header: React.FC = () => {
  const { i18n } = useTranslation();
  const locale = useGetLocale();
  const changeLanguage = useSetLocale();
  const { token } = useToken();
  const { data: user } = useGetIdentity<IUser>();
  const { mode, setMode } = useContext(ColorModeContext);

  const currentLocale = locale();

  const menu: MenuProps = {
    selectedKeys: currentLocale ? [currentLocale] : [],
    items: [...(i18n.languages || [])].sort().map((lang: string) => ({
      key: lang,
      icon: (
        <span style={{ marginRight: 8 }}>
          <Avatar size={16} src={`/images/flags/${lang}.svg`} />
        </span>
      ),
      label: lang === "en" ? "English" : "中文",
    })),
    onClick: ({ key: lang }) => changeLanguage(lang),
  };

  return (
    <AntdLayout.Header
      style={{
        backgroundColor: token.colorBgElevated,
        display: "flex",
        justifyContent: "flex-end",
        alignItems: "center",
        padding: "0px 24px",
        height: "64px",
      }}
    >
      <Dropdown menu={menu}>
        <Button type="link">
          <Space>
            <Avatar size={16} src={`/images/flags/${currentLocale}.svg`} />
            {currentLocale === "en" ? "English" : "中文"}
            <DownOutlined />
          </Space>
        </Button>
      </Dropdown>
      <Space>
        <Switch
          checkedChildren="🌛"
          unCheckedChildren="🔆"
          onChange={() => setMode(mode === "light" ? "dark" : "light")}
          defaultChecked={mode === "dark"}
        />
        <Space style={{ marginLeft: "8px" }} size="middle">
          {user?.name && <Text strong>{user.name}</Text>}
          {user?.avatar && <Avatar src={user?.avatar} alt={user?.name} />}
        </Space>
      </Space>
    </AntdLayout.Header>
  );
};
