import React from "react";
import { Layout, Switch, Button, Dropdown } from "antd";
import { UserOutlined, LogoutOutlined } from "@ant-design/icons";
import { useTheme } from "@/contexts/ThemeContext";
import { useAuth } from "@/contexts/AuthContext";
import { MenuTrigger } from "../Layout/MenuTrigger";
const { Header: AntHeader } = Layout;
import { LuSun } from "react-icons/lu";
import { GoMoon } from "react-icons/go";

const Header = ({ collapsed, setCollapsed }) => {
  const { isDarkMode, toggleTheme } = useTheme();
  const { user, logout } = useAuth();
  const handleLogout = async () => {
    try {
      await logout();
    } catch (error) {
      console.error("Logout error:", error);
    }
  };

  const userMenuItems = [
    // {
    //   key: "profile",
    //   icon: <UserOutlined />,
    //   label: "个人信息",
    // },
    {
      key: "logout",
      icon: <LogoutOutlined />,
      label: "退出登录",
      onClick: handleLogout,
    },
  ];

  return (
    <AntHeader
      style={{
        padding: 0,
        background: isDarkMode ? "#141414" : "#fff",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
      }}
    >
      <div className="flex items-center">
        <MenuTrigger
          collapsed={collapsed}
          setCollapsed={setCollapsed}
          isDarkMode={isDarkMode}
        />
      </div>

      <div className="flex items-center gap-4 mr-10 h-full select-none">
        <div className="flex items-center justify-center cursor-pointer h-full" onClick={toggleTheme}>
          {isDarkMode ? (
            <GoMoon className="text-2xl" />
          ) : (
            <LuSun className="text-2xl" />
          )}
        </div>

        <Dropdown
          menu={{ items: userMenuItems }}
          placement="bottomRight"
          trigger={["click"]}
        >
          <div className="flex gap-2 items-center justify-center cursor-pointer h-full">
            {user?.user_metadata?.picture ? (
              <img
                src={user?.user_metadata?.picture}
                alt="picture"
                className="w-8 h-8 rounded-full"
              />
            ) : (
              <div className="text-2xl bg-gray-400 dark:bg-gray-600 rounded-full flex justify-center items-center w-8 h-8 text-white pb-1">
                {user?.email.slice(0, 1)}
              </div>
            )}

            <p className="max-w-20 truncate">
              {user?.user_metadata?.name || user?.email?.split("@")[0]}
            </p>
          </div>
        </Dropdown>
      </div>
    </AntHeader>
  );
};

export default Header;
