"use client";
import useDesktop from "@/hooks/useDesktop";
import { Button, Popup } from "antd-mobile";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { forwardRef, memo, useEffect, useImperativeHandle, useRef } from "react";

/**
 * @description 检测pwa是否下载
 * if 下载 不弹窗 ， else 弹窗
 *
 */
export interface DesktopRefProps {
    onOpen: () => void;
    onClose: () => void;
}
interface Props {
    source?: "page" | "components";
}
const Desktop = forwardRef<DesktopRefProps, Props>(function Desktop(props, ref) {
    const { source = "page" } = props;
    const { cancel, isHasDesktop, downloadHandler, setHasDesktop } = useDesktop(source);
    const elementRef = useRef<HTMLElement | null>(null);

    const t = useTranslations("HomePage");

    useEffect(() => {
        elementRef.current = document.getElementById("app");
    }, []);
    useImperativeHandle(ref, () => {
        return {
            onClose: () => setHasDesktop(false),
            onOpen: () => {
                setHasDesktop(true);
            },
        };
    });

    return (
        <Popup
            visible={!!isHasDesktop}
            getContainer={elementRef.current}
            bodyStyle={{ padding: "0.2rem", background: "#fff" }}
        >
            <div className={"flex text-[0.12rem] text-[#8d8d8d]"}>
                <Image
                    src={"/icon-192x192.png"}
                    alt={"logo"}
                    className={"mr-[10px] flex-shrink-0"}
                    width={80}
                    height={80}
                />
                {t("saveTips")}
            </div>
            <div className={"mb-[0.16rem] mt-[0.1rem] text-right"}>
                <Button
                    color="default"
                    className={"mr-[10px]"}
                    style={{ "--text-color": "#8d8d8d" }}
                    fill="none"
                    onClick={cancel}
                >
                    {t("cancel")}
                </Button>
                <Button
                    color="primary"
                    style={{
                        "--text-color": "#ff6a01",
                        "--border-color": "#ff6a01",
                        "--border-radius": "10px",
                    }}
                    fill="outline"
                    onClick={downloadHandler}
                >
                    {t("save")}
                </Button>
            </div>
        </Popup>
    );
});
export default memo(Desktop);
