const express = require("express");
const { body } = require("express-validator");

const CustomersModel = require("../../../models/Customers");

const {
  accountLogin,
  accountCreate,
  forgotPassword,
  resetPassword,
  updateCredentials,
  verifyEmail,
  generateQrRecord,
  checkQrRecordStatus,
  updateQrRecordAsAuthenticated
} = require("../../../controllers/accounts");

const isAuth = require("../../../middlewares/authorization");

const validateInput = require("../../../middlewares/validation");

const router = express.Router();

router.post("/login", [body("email").notEmpty().isEmail(), body("password").notEmpty()], validateInput, accountLogin);

router.post(
  "/register",
  [
    body("type").notEmpty().isString(),
    body("hardwareName").optional(),
    body("firstName").notEmpty(),
    body("lastName").notEmpty(),
    body("email").notEmpty().isEmail(),
    body("password").notEmpty(),
    body("confirmPassword")
      .notEmpty()
      .custom((value, { req }) => {
        if (value !== req.body.password) {
          throw new Error("Passwords do not matched!");
        }
        return true;
      }),
    body("phone").optional(),
    body("address").notEmpty(),
    body("longitude").optional(),
    body("latitude").optional(),
  ],
  validateInput,
  accountCreate
);
router.get("/verify-email/:token", verifyEmail);
router.post("/forgot-password", forgotPassword);
router.post("/reset-password/:token", resetPassword);
router.put("/update-credentials/:customerID", isAuth, updateCredentials);

router.get("/reset-password/:token", (req, res) => {
  const htmlForm = `
  <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Password Reset</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f7f7f7;
      margin: 0;
      padding: 0;
    }

    .container {
      max-width: 400px;
      margin: 50px auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 8px;
      background-color: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .logo {
      display: block;
      margin: 0 auto 20px;
      width: 200px;
    }

    h2 {
      margin-top: 0;
      font-size: 24px;
      color: #333;
    }

    .form-group {
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      color: #555;
    }

    input[type="password"] {
      width: 94%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }

    button[type="submit"] {
      width: 100%;
      padding: 10px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    .popup {
      display: none;
      margin-top: 10px;
      padding: 10px;
      border-radius: 5px;
    }

    .error-message {
      color: #dc3545;
      background-color: #f8d7da;
    }

    .success-message {
      color: #28a745;
      background-color: #d4edda;
    }
  </style>
</head>
<body>
  <div class="container">
    <img src="https://buildhub.ph/img/buildhub.png" alt="BuildHub Logo" class="logo">
    <h2>Password Reset</h2>
    <form id="reset-password-form">
      <div class="form-group">
        <label for="new-password">New Password</label>
        <input type="password" id="new-password" name="newPassword" required>
      </div>
      <div class="form-group">
        <label for="confirm-password">Confirm Password</label>
        <input type="password" id="confirm-password" name="confirmPassword" required>
      </div>
      <button type="submit">Reset Password</button>
    </form>
    <div id="error-message" class="popup error-message">
      <!-- Error message will be displayed here -->
    </div>
    <div id="success-message" class="popup success-message">
      <!-- Success message will be displayed here -->
    </div>
  </div>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
      const resetPasswordForm = document.getElementById("reset-password-form");
      const errorMessage = document.getElementById("error-message");
      const successMessage = document.getElementById("success-message");

      resetPasswordForm.addEventListener("submit", async function (event) {
        event.preventDefault();

        const newPassword = document.getElementById("new-password").value;
        const confirmPassword = document.getElementById("confirm-password").value;

        try {
          const response = await fetch("/api/v1/accounts/reset-password/${req.params.token}", {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({ newPassword, confirmPassword })
          });

          const data = await response.json();
          if (response.ok) {
            successMessage.textContent = data.message;
            successMessage.style.display = "block";
            errorMessage.style.display = "none";
          } else {
            errorMessage.textContent = data.error;
            errorMessage.style.display = "block";
            successMessage.style.display = "none";
          }
        } catch (error) {
          errorMessage.textContent = "An error occurred while processing your request.";
          errorMessage.style.display = "block";
          successMessage.style.display = "none";
        }
      });
    });
  </script>
</body>
</html>

  `;
  res.send(htmlForm);
});


router.get("/authentication/generate-qr", generateQrRecord);
router.get("/authentication/qr-status", checkQrRecordStatus);
router.post("/authentication/qr-update-status", isAuth, updateQrRecordAsAuthenticated);
module.exports = router;
