import { FC, useEffect, useRef, useState } from "react";
import closeIcon from "@/assets/icons/close_btn.svg";
import restartModalData from "@content/modals/restart_modal.json";
import "./DialogWrapper.scss";
import { RestartModal } from "@/components/RestartModal/RestartModal";
import { useContentWithTrad } from "@/hooks/useContentWithTrad";

interface DialogWrapperProps {
    onClose: () => void;
    children?: React.ReactNode;
    title?: string;
    hasCloseButton?: boolean;
    isDemo?: boolean;
}

export const DialogWrapper: FC<DialogWrapperProps> = ({
    onClose,
    children,
    title = "Modal Dialog",
    hasCloseButton = false,
    isDemo = false,
}) => {
    const [isClosing, setIsClosing] = useState(false);
    const dialogRef = useRef<HTMLDialogElement>(null);
    const timeoutRef = useRef<number | null>(null);
    const restartModalContent = useContentWithTrad(restartModalData);

    useEffect(() => {
        const dialog = dialogRef.current;
        if (!dialog) return;
        dialog.showModal();

        return () => {
            if (timeoutRef.current !== null) {
                window.clearTimeout(timeoutRef.current);
                timeoutRef.current = null;
            }
        };
    }, []);

    const handleClose = () => {
        setIsClosing(true);
        timeoutRef.current = window.setTimeout(() => {
            onClose();
            dialogRef.current?.close();
        }, 400);
    };

    return (
        <div
            className={`dialog-wrapper ${
                isClosing ? "dialog-wrapper--closing" : ""
            }`}>
            <div className="dialog-wrapper__overlay" onClick={handleClose} />
            <dialog
                ref={dialogRef}
                className={`dialog-wrapper__content ${
                    isDemo && "dialog-wrapper__content--is-demo"
                }`}>
                {title !== "Modal Dialog" && (
                    <header
                        className={`dialog-wrapper__header ${
                            isDemo && "dialog-wrapper__header--is-demo"
                        }`}>
                        <h2 className="dialog-wrapper__title">
                            {isDemo ? restartModalContent.title : title}
                        </h2>
                    </header>
                )}
                {hasCloseButton && (
                    <button
                        className="dialog-wrapper__close"
                        onClick={handleClose}
                        aria-label="Fermer">
                        <img src={closeIcon} alt="fermer modale" />
                    </button>
                )}
                {isDemo ? <RestartModal onClose={handleClose} /> : children}
            </dialog>
        </div>
    );
};
