"use client";
import { usePathname, useRouter } from "@/i18n";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import { FC, PropsWithChildren, ReactNode, useEffect, useState } from "react";
import styles from "./style.module.scss";

import clearCache from "./actions";

/**
 * @description 自定义头部返回组件
 * @param {string} title header标题
 * @param {ReactNode} children 插槽内容
 * @param {() => ReactNode} headerRender 自定义渲染
 */
export interface HeaderBackProps {
    title?: string;
    children?: ReactNode;
    showBack?: Boolean;
    headerRender?: () => ReactNode;
    className?: string;
}

const HeaderBack: FC<PropsWithChildren<HeaderBackProps>> = ({
    title = "",
    showBack = true,
    children,
    className,
}) => {
    const t = useTranslations("HeaderBack");

    const iconClassName1 = clsx(
        {
            [styles.iconfontIcon1]: true,
        },
        "iconfont icon-xiangzuo1"
    );
    const iconClassName2 = clsx(
        {
            [styles.iconfontIcon2]: true,
        },
        "iconfont icon-company_nav_icon_home"
    );

    let pathname = usePathname();
    let [selfTitle, setSelfTitle] = useState("");
    const setSelfTitleFun = () => {
        if (pathname == "/deposit") {
            setSelfTitle(t("Depósito"));
            return;
        }
        setSelfTitle("");
    };
    useEffect(() => {
        setSelfTitleFun();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pathname]);

    const router = useRouter();
    const goPage = async (path = "") => {
        if (path) {
            await clearCache();
            router.replace("/");
            return;
        }
        router.back();
    };
    const cls = clsx(styles.headerBack, className);
    return (
        <div className={cls}>
            <div className={styles.left}>
                {showBack && <span className={iconClassName1} onClick={() => goPage()}></span>}
            </div>
            {(title || selfTitle) && <span className={styles.title}>{title || selfTitle}</span>}
            {children}
            <span className={styles.right} onClick={() => goPage("home")}>
                <span className={iconClassName2}></span>
            </span>
        </div>
    );
};

export default HeaderBack;
