import React, { useState, useEffect } from "react";
import { useLogout, useGetIdentity, useUpdatePassword } from "@refinedev/core";
import { Layout, Button, Space, Typography, Avatar, theme, Dropdown, MenuProps, Tooltip } from "antd";
import { LogoutOutlined, UserOutlined, DownOutlined, SunOutlined, MoonOutlined, CameraOutlined, LockOutlined, GlobalOutlined, MessageOutlined } from "@ant-design/icons";
import { useColorMode, GlobalSearch, ChangePhotoModal, ChangePasswordModal } from "@cundi/refine-xaf";
import { useTranslation } from "react-i18next";
import { useChatPanel } from "./ChatPanel";

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

/**
 * Custom Header that includes the chat toggle button
 * This is a modified version of the Header from @cundi/refine-xaf
 */
export const HeaderWithChat: React.FC = () => {
    const { mutate: logout } = useLogout();
    const { mutate: updatePassword } = useUpdatePassword();
    const { data: user } = useGetIdentity<any>();
    const { mode, setMode } = useColorMode();
    const { token } = useToken();
    const { isOpen: isChatOpen, toggle: toggleChat } = useChatPanel();

    const { t: translate, i18n } = useTranslation();
    const currentLocale = i18n.language;

    const handleLanguageChange = (lang: string) => {
        i18n.changeLanguage(lang);
    };

    // Track auth provider
    const [authProvider, setAuthProvider] = useState<string | null>(null);

    useEffect(() => {
        if (user) {
            setAuthProvider(localStorage.getItem("auth_provider"));
        }
    }, [user]);

    // Photo Modal State
    const [isPhotoModalOpen, setIsPhotoModalOpen] = useState(false);

    // Password Modal State
    const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);

    const menuItems: MenuProps["items"] = [
        {
            key: "user-info",
            label: (
                <Space direction="vertical" size={0}>
                    <Text strong>{user?.name}</Text>
                </Space>
            ),
            icon: <UserOutlined />,
            disabled: true,
            style: { cursor: "default", color: token.colorText },
        },
        {
            type: "divider",
        },
        {
            key: "change-photo",
            label: translate("components.header.menu.changePhoto", "Change Photo"),
            icon: <CameraOutlined />,
            onClick: () => {
                setIsPhotoModalOpen(true);
            },
        },
        {
            key: "change-password",
            label: authProvider === "keycloak"
                ? translate("components.header.menu.manageAccount", "Manage Account in Keycloak")
                : translate("components.header.menu.changePassword", "Change Password"),
            icon: <LockOutlined />,
            onClick: () => {
                if (authProvider === "keycloak") {
                    const env = (import.meta as any).env;
                    const keycloakUrl = env?.VITE_KEYCLOAK_URL || "http://localhost:8080";
                    const realm = env?.VITE_KEYCLOAK_REALM || "cundi";
                    window.open(`${keycloakUrl}/realms/${realm}/account`, "_blank");
                } else {
                    setIsPasswordModalOpen(true);
                }
            },
        },
        {
            type: "divider",
        },
        {
            key: "theme",
            label: mode === "light"
                ? translate("components.header.theme.dark", "Dark Theme")
                : translate("components.header.theme.light", "Light Theme"),
            icon: mode === "light" ? <MoonOutlined /> : <SunOutlined />,
            onClick: () => setMode(mode === "light" ? "dark" : "light"),
        },
        {
            key: "logout",
            label: translate("components.header.menu.logout", "Logout"),
            icon: <LogoutOutlined />,
            onClick: () => logout(),
        }
    ];

    return (
        <Layout.Header
            style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                padding: "0 24px",
                height: "64px",
                backgroundColor: token.colorBgElevated,
                position: "sticky",
                top: 0,
                zIndex: 1,
            }}
        >
            <Space size="middle">
                <div>
                    <GlobalSearch width={300} placeholder={translate("components.globalSearch.placeholder", "Search...")} />
                </div>

                {/* Chat Toggle Button */}
                <Tooltip title={translate("chat.toggleTooltip", "Toggle AI Chat")}>
                    <Button
                        type={isChatOpen ? "primary" : "text"}
                        icon={<MessageOutlined />}
                        onClick={toggleChat}
                    />
                </Tooltip>

                <Dropdown
                    menu={{
                        items: [
                            {
                                key: "en",
                                label: translate("components.header.language.en", "English"),
                                onClick: () => handleLanguageChange("en"),
                                disabled: currentLocale === "en",
                            },
                            {
                                key: "zh-TW",
                                label: translate("components.header.language.zh-TW", "繁體中文"),
                                onClick: () => handleLanguageChange("zh-TW"),
                                disabled: currentLocale === "zh-TW",
                            },
                        ]
                    }}
                    trigger={["click"]}
                >
                    <Button type="text" icon={<GlobalOutlined />}>
                        {currentLocale === "zh-TW" ? "繁體中文" : "English"} <DownOutlined />
                    </Button>
                </Dropdown>

                <Dropdown menu={{ items: menuItems }} trigger={["click"]}>
                    <Button type="text" style={{ height: 48 }}>
                        <Space>
                            <Avatar src={user?.avatar} alt={user?.name} icon={<UserOutlined />} />
                            <Text>{user?.name}</Text>
                            <DownOutlined style={{ fontSize: 12 }} />
                        </Space>
                    </Button>
                </Dropdown>
            </Space>

            {/* Photo Modal */}
            <ChangePhotoModal
                open={isPhotoModalOpen}
                onClose={() => setIsPhotoModalOpen(false)}
                user={user}
            />

            <ChangePasswordModal
                open={isPasswordModalOpen}
                onClose={() => setIsPasswordModalOpen(false)}
            />
        </Layout.Header>
    );
};
