<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>User List</title> 
    <!--Styles-->
    <style>
      .container {
        margin: 0 auto;
        max-width: 800px;
        padding: 20px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); 
        background: #f9f9f9; 
      }
    
      .user-card {
        background-color: #ffffff; 
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 5px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 
        border-left: 5px solid #bfc1c2; 
        background-image: linear-gradient(to right, #e8e9eb, #f5f5f5); 
      }
    
      .user-card h2 {
        color: #bfc1c2; 
        text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2); 
      }
    
      .email, .age {
        color: #4f4f4f; 
      }
    
      .user-card form, .email-update-form {
        margin-top: 10px;
        background: rgba(255, 255, 255, 0.8); 
        padding: 10px;
        border-radius: 5px;
        box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1); 
      }
    
      button {
        background-image: linear-gradient(to bottom, #e8e9eb, #bfc1c2); 
        border: none;
        color: #333; 
        padding: 10px 20px;
        margin: 5px;
        border-radius: 5px;
        cursor: pointer;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); 
        transition: transform 0.1s ease-in-out; 
      }
    
      button:active {
        transform: translateY(2px); 
      }
    </style>
    
    
  </head>
  <body>
    <div class="container">
      <h1>User List</h1>
      <% users.forEach(user => { %>
      <div class="user-card">
        <h2>Username:</h2>
        <p><%= user.username %></p>
        <h2>Email Address:</h2>
        <p class="email"><%= user.email %></p>
        <h2>Age:</h2>
        <p class="age"><%= user.age %></p>

        <!-- Form for updating user data -->
        <form
          class="update-form"
          action="/api/users/<%= user.id %>?_method=PUT"
          method="POST"
        >
          <input type="hidden" name="_method" value="PUT" />
          <label for="update-username-<%= user.id %>">New Username:</label>
          <input
            type="text"
            id="update-username-<%= user.id %>"
            name="username"
          />
          <label for="update-email-<%= user.id %>">New Email:</label>
          <input type="email" id="update-email-<%= user.id %>" name="email" />
          <label for="update-age-<%= user.id %>">New Age:</label>
          <input type="number" id="update-age-<%= user.id %>" name="age" />
          <button type="submit">Update</button>
        </form>

        <!-- Input for PATCH operation to update user email -->
        <div>
          <label for="email-patch-<%= user.id %>">Update Email:</label>
          <input
            type="email"
            id="email-patch-<%= user.id %>"
            placeholder="New email"
          />
          <button
            onclick="updateUserEmail('<%= user.id %>', document.getElementById('email-patch-<%= user.id %>').value)"
          >
            Update Email
          </button>
        </div>

        <!-- Delete button -->
        <button onclick="deleteUser('<%= user.id %>')">Delete User</button>
      </div>
      <% }); %>

      <!-- Form for adding a new user -->
      <div class="user-card">
        <h2>Add New User</h2>
        <form id="add-user-form" action="/api/users" method="POST">
          <label for="add-username">Username:</label>
          <input type="text" id="add-username" name="username" required />
          <label for="add-email">Email:</label>
          <input type="email" id="add-email" name="email" required />
          <label for="add-age">Age:</label>
          <input type="number" id="add-age" name="age" required />
          <button type="submit">Add User</button>
        </form>
      </div>
    </div>

    <script>
      // Handle form submissions for updates and additions
      function handleFormSubmit(event) {
        event.preventDefault();
        const form = event.target;
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        fetch(form.action, {
          method: form.method.toUpperCase(),
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        })
          .then((response) => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
          })
          .then((responseData) => {
            console.log(responseData);
            alert("Operation was successful!");
            window.location.reload();
          })
          .catch((error) => {
            console.error("Operation failed:", error);
          });
      }

      // Function for PATCH operation to update user email
      function updateUserEmail(userId, newEmail) {
        fetch(`/api/users/${userId}`, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ email: newEmail }),
        })
          .then((response) => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
          })
          .then((responseData) => {
            console.log("Email update successful:", responseData);
            alert("User's email has been successfully updated!");
            window.location.reload();
          })
          .catch((error) => {
            console.error("Email update failed:", error);
          });
      }

      // Handle user deletions
      function deleteUser(userId) {
        if (confirm("Are you sure you want to delete this user?")) {
          fetch(`/api/users/${userId}?_method=DELETE`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
          })
            .then((response) => {
              if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
              }
              return response.json();
            })
            .then((responseData) => {
              console.log(responseData);
              alert("User successfully deleted.");
              window.location.reload();
            })
            .catch((error) => {
              console.error("Deletion failed:", error);
            });
        }
      }

      // Attach event listeners to forms for submission
      document.querySelectorAll("form").forEach((form) => {
        form.addEventListener("submit", handleFormSubmit);
      });
    </script>
  </body>
</html>
