import Modal from "@mui/material/Modal";
import Fade from "@mui/material/Fade";
import styles from "./styles.module.scss";
import { useEffect, useState } from "react";
import Grow from "@mui/material/Grow";
import symbol from "@assets/symbol-defs.svg";
import { localStorageGet, localStorageSet } from "@utils/helpers";

const i18n = global.i18n;

const WMusicSettings = ({ close }) => {
    // 确保从 localStorage 正确读取初始值
    const getInitialMusicStatus = () => {
        const stored = localStorageGet("music");
        // 如果 localStorage 中没有值，默认返回 true
        if (stored === null || stored === undefined || stored === '') return true;
        // 如果存储的是字符串，解析它；如果是布尔值，直接使用
        return typeof stored === 'string' ? JSON.parse(stored) : stored;
    };

    const [open, setOpen] = useState(false);

    const [music, setMusic] = useState(getInitialMusicStatus());

    const show = (type) => {
        setOpen(true);
    };
    const hide = () => {
        setOpen(false);
    };
    const onClose = () => {
        hide();
        // 关闭后重置为保存的状态，而不是临时的修改
        setTimeout(() => {
            setMusic(getInitialMusicStatus());
        }, 500);
    };
    useEffect(() => {
        const musicSettings = {
            show,
            hide
        };
        global.musicSettings = musicSettings;
    }, []);

    const handleClickMusic = () => {
        setMusic(!music);
    };

    const handleClickSave = () => {
        localStorageSet("music", !music);
        hide();
    };


    const renderMain = () => {
        return (
            <Grow in={open} timeout={500}>
                <div className={styles.content}>
                    <div className={`${styles.item} ${music ? "" : styles.off}`}>
                        <svg width={48} height={48} className={styles.icon}>
                            <use xlinkHref={`${symbol}#icon_music`} />
                        </svg>
                        <div className={styles.title}>Music</div>
                        <div className={styles.switch} onClick={handleClickMusic}>
                            <div className={styles.button}></div>
                        </div>
                    </div>

                    <div className={styles.save} onClick={handleClickSave}>
                        Save
                    </div>
                </div>
            </Grow>
        );
    };
    return (
        <>
            <Modal open={open} onClose={onClose} closeAfterTransition>
                <Fade in={open} timeout={500}>
                    <div className={styles.container}>
                        {
                            renderMain()
                        }
                    </div>
                </Fade>
            </Modal>
        </>
    );
};
export default WMusicSettings;