"use client";
import React from "react";
import {Layout} from "antd";
import AppDropdown from "@/components/ui/dropdown";
import AppTypography from "@/components/ui/typography";
import {useTranslations} from "next-intl";
import {cn} from "@/lib/utils";
import AppAvatar from "@/components/ui/avatar";
import {UserDetail, UserType} from "@/types/user";
import AppTag from "@/components/ui/tag";
import {useAppDispatch, useAppSelector} from "@/lib/redux/hooks";
import {
    clearAuthInfo,
    doLogout,
    getAuthInfo,
} from "@/lib/redux/features/auth";
import {LogoutResponse} from "@/types/auth";
import {ResponseStatus, STORAGE_KEYS} from "@/types/common";
import StorageHelper from "@/lib/storeHelper";
import {Languages, LogOut, UserCog} from "lucide-react";
import {clearUserDetail} from "@/lib/redux/features/user";
import {useMounted} from "@/hooks/useMounted";
import AppButton from "@/components/ui/button";
import {useRouter, usePathname} from "@/i18n/routing";

const {Header} = Layout;

const AppHeader: React.FC = () => {
    const t = useTranslations("ManageAccountPage");
    const router = useRouter();
    const pathname = usePathname();
    const dispatch = useAppDispatch();
    const authInfo = useAppSelector(getAuthInfo);
    const mounted = useMounted();
    const locale = StorageHelper.getCookie(STORAGE_KEYS.NEXT_LOCALE) || "ja";

    const handleLogoClick = () => {
        router.push(`/admin/app`);
    };

    const getUserDisplayName = () => {
        if (!mounted) return "";
        if (!authInfo?.firstName && !authInfo?.lastName) return authInfo?.email;
        return `${authInfo?.firstName || ""} ${authInfo?.lastName || ""}`;
    };

    const handleRenderUserRole = (userType: UserType) => {
        switch (userType) {
            case UserType.ADMIN:
                return (
                    <AppTag color="#fb923c" className="ml-3">
                        {t("user_type.SUPER_ADMIN")}
                    </AppTag>
                );
            case UserType.USER:
                return (
                    <AppTag color="#fb923c" className="ml-3">
                        {t("user_type.USER")}
                    </AppTag>
                );
            default:
                return "-";
        }
    };

    const handleRenderDropdown = (menu) => {
        const menuStyle = {
            boxShadow: "none",
        };
        return (
            <div className="w-[280px] bg-white rounded-lg shadow">
                <div className="py-4 px-2 border-b border-neutral-200">
                    <div className="max-w-[260px] text-nowrap overflow-hidden text-ellipsis">
                        <AppTypography className="ml-3 !text-neutral-600 text-lg font-semibold">
                            {t("hi_username", {
                                username: getUserDisplayName(),
                            })}
                        </AppTypography>
                    </div>
                    <div className="ml-3">
                        {authInfo?.userType && handleRenderUserRole(authInfo?.userType)}
                    </div>
                </div>
                <div className="p-2">
                    {React.cloneElement(menu, {
                        style: menuStyle,
                    })}
                </div>
            </div>
        );
    };

    const handleLogout = async () => {
        const result = await dispatch(doLogout());
        const payload = result?.payload as LogoutResponse;
        if (payload && payload.status === ResponseStatus.SUCCESS) {
            dispatch(clearAuthInfo());
            dispatch(clearUserDetail());
            StorageHelper.removeCookie(STORAGE_KEYS.token);
            StorageHelper.removeLocalItem(STORAGE_KEYS.user);
            router.push("/sign-in");
        }
    };

    const handleRenderLocaleMenu = () => {
        const supportedLocales = ["en", "ja"];

        const handleSwitchLanguage = (newLocale: string) => {
            if (locale !== newLocale) {
                StorageHelper.setCookie(STORAGE_KEYS.NEXT_LOCALE, newLocale, {
                    path: "/",
                    maxAge: 31536000,
                });
                router.replace(pathname, {locale: newLocale});
            }
        };

        return [
            {
                key: "ja",
                label: (
                    <AppTypography className="text-neutral-600">日本語</AppTypography>
                ),
                onClick: () => handleSwitchLanguage("ja"),
            },
            {
                key: "en",
                label: (
                    <AppTypography className="text-neutral-600">English</AppTypography>
                ),
                onClick: () => handleSwitchLanguage("en"),
            },
        ];
    };

    const handleRenderMenu = () => {
        return [
            {
                key: "manage-account",
                label: (
                    <AppTypography className="text-neutral-600">
                        {t("title")}
                    </AppTypography>
                ),
                icon: <UserCog size={20}/>,
                onClick: () => {
                    router.push(`/admin/manage-account/${authInfo?.id}`);
                },
            },
            {
                key: "logout",
                label: (
                    <AppTypography className="text-neutral-600">
                        {t("logout")}
                    </AppTypography>
                ),
                icon: <LogOut size={20}/>,
                onClick: () => {
                    handleLogout();
                },
            },
        ];
    };

    return (
        <Header
            style={{
                background: "#ffffff",
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
                padding: "0 16px",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                height: "64px",
                width: "100%",
                position: "sticky",
                top: 0,
                zIndex: 1,
            }}
        >
            <div className="w-full flex justify-between items-center">
                <div
                    className="p-2 text-xs md:text-lg font-bold text-center text-neutral-800 cursor-pointer"
                    onClick={handleLogoClick}
                >
                    iDoc Shopify App
                </div>
                {mounted && (
                    <div className="flex justify-center items-center gap-2">
                        <div>
                            <AppTypography
                                className="block !text-neutral-600 text-lg font-semibold max-w-[160px] text-nowrap overflow-hidden text-ellipsis">
                                {t("username", {
                                    username: getUserDisplayName(),
                                })}
                            </AppTypography>
                        </div>
                        <div>
                            <AppDropdown
                                overlayClassName="manage-account-dropdown"
                                menu={{
                                    items: handleRenderMenu(),
                                }}
                                trigger={["click"]}
                                dropdownRender={(menu) => handleRenderDropdown(menu)}
                            >
                                <AppAvatar
                                    size={40}
                                    className={cn("bg-neutral-400 cursor-pointer")}
                                />
                            </AppDropdown>
                        </div>
                        <AppDropdown
                            overlayClassName="manage-account-dropdown"
                            menu={{
                                items: handleRenderLocaleMenu(),
                                selectedKeys: [locale],
                            }}
                            trigger={["click"]}
                            className={"flex items-center"}
                        >
                            <AppButton
                                type="text"
                                shape="circle"
                                size="large"
                                className="!flex items-center"
                            >
                                <Languages size={24}/>
                            </AppButton>
                        </AppDropdown>
                    </div>
                )}
            </div>
        </Header>
    );
};

export default AppHeader;
