// components/modales/settingsModal/handlers/handleReboot.ts
const handleReboot = async (newIp: string | null = null): Promise<void> => {
  const showWaitPage = () => {
    const waitHTML = `
      <!DOCTYPE html>
      <html lang="de">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bitte warten...</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f9;
            color: #333;
          }
          .message {
            text-align: center;
          }
          .progress-container {
            width: 100%;
            background-color: #ddd;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 20px;
          }
          .progress-bar {
            height: 20px;
            width: 0;
            background-color: #3498db;
            transition: width 0.3s;
          }
        </style>
      </head>
      <body>
        <div class="message">
          <p>Bitte warten, CPL wird neu gestartet...</p>
          <div class="progress-container">
            <div class="progress-bar" id="progress-bar"></div>
          </div>
        </div>
      </body>
      </html>
    `;
    document.documentElement.innerHTML = waitHTML;

    let progress = 0;
    const progressBar = document.getElementById("progress-bar");
    if (progressBar) {
      const interval = setInterval(() => {
        progress += 1;
        progressBar.style.width = progress + "%";
        if (progress >= 100) {
          clearInterval(interval);
        }
      }, 300);
    } else {
      console.error("Progress-Bar-Element nicht gefunden.");
    }
  };

  if (window.confirm("Sind Sie sicher, dass Sie den CPL neu starten möchten?")) {
    showWaitPage();

    const baseRedirectURL = newIp ? `https://${newIp}` : window.location.origin;
    const redirectPath =
      process.env.NODE_ENV === "production" ? "/dashboard.html" : "/dashboard";

    setTimeout(() => {
      window.location.href = `${baseRedirectURL}${redirectPath}`;
    }, 33000);

    const url = `${window.location.origin}/CPL?wait2reboot.html&BOOT=1`;
    console.log(url);

    fetch(url, { method: "GET" })
      .then(() => {
        console.log("Neustart-Anfrage erfolgreich gesendet.");
      })
      .catch((error) => {
        console.error("Fehler beim Senden der Neustartanfrage:", error);
      });
  }
};

export default handleReboot;
