document.addEventListener("DOMContentLoaded", () => {
  const apiUrl = "http://localhost:8080"; // Replace with your actual backend URL

  // Fetch and populate table data
  function loadTables() {
    fetch(`${apiUrl}/tables`)
      .then((response) => response.json())
      .then((tables) => {
        const tableBody = document.querySelector("#tables tbody");
        tableBody.innerHTML = ""; // Clear existing rows

        tables.forEach((table) => {
          const row = document.createElement("tr");
          row.innerHTML = `
            <td>${table.id}</td>
            <td>${table.name}</td>
            <td>${table.max_people}</td>
            <td>${table.room}</td>
            <td>
              <button data-id="${table.id}" class="edit">Edit</button>
              <button data-id="${table.id}" class="delete">Delete</button>
            </td>
          `;
          tableBody.appendChild(row);
        });
      })
      .catch((error) => console.error("Error loading tables:", error));
  }

// Handle form submission to create or update a table
document.querySelector("#table-form").addEventListener("submit", (e) => {
  e.preventDefault();

  const id = parseInt(document.querySelector("#table-id").value, 10) || undefined;
  const name = parseInt(document.querySelector("#table-name").value, 10); // Adjusted for name as integer
  const maxPeople = parseInt(document.querySelector("#table-max-people").value, 10);
  const room = document.querySelector("#table-room").value;

  const method = id ? "PUT" : "POST";
  const endpoint = id ? `/table` : `/table`;

  fetch(`${apiUrl}${endpoint}`, {
    method,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ id, name, max_people: maxPeople, room }),
  })
    .then((response) => {
      if (!response.ok) {
        return response.text().then((text) => {
          if (text.trim() === "") {
            throw new Error("Empty response from server");
          }
          try {
            const errorJson = JSON.parse(text);
            throw new Error(errorJson.message || "Failed to save table");
          } catch {
            throw new Error("Unexpected server response: " + text);
          }
        });
      }
      return response.text().then((text) => {
        if (text.trim() === "") {
          return {}; // Handle empty body for successful responses
        }
        return JSON.parse(text);
      });
    })
    .then(() => {
      document.querySelector("#table-form").reset();
      loadTables();
      alert(`Table ${id ? 'updated' : 'created'} successfully.`);
    })
    .catch((error) => {
      console.error("Error saving table:", error);
      alert(`Failed to save table: ${error.message}`);
    });
});

  // Handle table row actions (edit/delete)
  document.querySelector("#tables").addEventListener("click", (e) => {
    const button = e.target;
    const id = button.dataset.id;

    if (button.classList.contains("edit")) {
      fetch(`${apiUrl}/table/${id}`)
        .then((response) => response.json())
        .then((table) => {
          document.querySelector("#table-id").value = table.id;
          document.querySelector("#table-name").value = table.name;
          document.querySelector("#table-max-people").value = table.max_people;
          document.querySelector("#table-room").value = table.room;
        })
        .catch((error) => console.error("Error fetching table:", error));
    } else if (button.classList.contains("delete")) {
      fetch(`${apiUrl}/table/${id}`, { method: "DELETE" })
        .then(() => loadTables())
        .catch((error) => console.error("Error deleting table:", error));
    }
  });

   // Handle find table by ID
  document.querySelector("#find-table-form").addEventListener("submit", (e) => {
    e.preventDefault();

    const id = parseInt(document.querySelector("#find-table-id").value, 10);

    fetch(`${apiUrl}/table/${id}`)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`Table with ID ${id} not found`);
        }
        return response.json();
      })
      .then((table) => {
        alert(`Table ID: ${table.id}\nName (Number): ${table.name}\nMax People: ${table.max_people}\nRoom: ${table.room}`);
      })
      .catch((error) => {
        alert(`Error: ${error.message}`);
        console.error("Error finding table:", error);
      });
  });

  // Initial load
  loadTables();

  // Fetch and populate booking data
  function loadBookings() {
    fetch(`${apiUrl}/bookings`)
      .then((response) => response.json())
      .then((bookings) => {
        const bookingBody = document.querySelector("#bookings tbody");
        bookingBody.innerHTML = ""; // Clear existing rows

        bookings.forEach((booking) => {
          const row = document.createElement("tr");
          row.innerHTML = `
            <td>${booking.id}</td>
            <td>${booking.id_tables}</td>
            <td>${booking.reservation}</td>
            <td>${booking.time_reserve}</td>
            <td>${booking.who_booked}</td>
            <td>
              <button data-id="${booking.id}" class="edit">Edit</button>
              <button data-id="${booking.id}" class="delete">Delete</button>
            </td>
          `;
          bookingBody.appendChild(row);
        });
      })
      .catch((error) => console.error("Error loading bookings:", error));
  }

  // Handle form submission to create or update a booking
  document.querySelector("#booking-form").addEventListener("submit", (e) => {
    e.preventDefault();

    const id = parseInt(document.querySelector("#booking-id").value, 10) || undefined;
    const tableId = parseInt(document.querySelector("#booking-table-id").value, 10);
    const reservationDatetime = String(document.querySelector("#reservation-datetime").value);
    const timeReserve = document.querySelector("#time-reserve").value;
    const whoBooked = document.querySelector("#who-booked").value;

    const method = id ? "PUT" : "POST";
    const endpoint = id ? `/booking` : `/booking`;

    fetch(`${apiUrl}${endpoint}`, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, id_tables: tableId, reservation: reservationDatetime, time_reserve: timeReserve, who_booked: whoBooked }),
    })
    .then((response) => {
      if (!response.ok) {
        return response.text().then((text) => {
          if (text.trim() === "") {
            throw new Error("Empty response from server");
          }
          try {
            const errorJson = JSON.parse(text);
            throw new Error(errorJson.message || "Failed to save table");
          } catch {
            throw new Error("Unexpected server response: " + text);
          }
        });
      }
      return response.text().then((text) => {
        if (text.trim() === "") {
          return {}; // Handle empty body for successful responses
        }
        return JSON.parse(text);
      });
    })
    .then(() => {
      document.querySelector("#booking-form").reset();
      loadBookings();
      alert(`Booking ${id ? 'updated' : 'created'} successfully.`);
    })
    .catch((error) => {
      console.error("Error saving booking:", error);
      alert(`Failed to save booking: ${error.message}`);
    });
  });

  // Handle booking row actions (edit/delete)
  document.querySelector("#bookings").addEventListener("click", (e) => {
    const button = e.target;
    const id = button.dataset.id;

    if (button.classList.contains("edit")) {
      fetch(`${apiUrl}/booking/${id}`)
        .then((response) => response.json())
        .then((booking) => {
          document.querySelector("#booking-id").value = booking.id;
          document.querySelector("#booking-table-id").value = booking.id_tables;
          document.querySelector("#reservation-datetime").value = booking.reservation;
          document.querySelector("#time-reserve").value = booking.time_reserve;
          document.querySelector("#who-booked").value = booking.who_booked;
        })
        .catch((error) => console.error("Error fetching booking:", error));
    } else if (button.classList.contains("delete")) {
      fetch(`${apiUrl}/booking/${id}`, { method: "DELETE" })
        .then(() => loadBookings())
        .catch((error) => console.error("Error deleting booking:", error));
    }
  });

  // Handle find booking by ID
  document.querySelector("#find-booking-form").addEventListener("submit", (e) => {
    e.preventDefault();

    const id = document.querySelector("#find-booking-id").value;

    fetch(`${apiUrl}/booking/${id}`)
      .then((response) => {
        if (!response.ok) throw new Error("Booking not found");
        return response.json();
      })
      .then((booking) => {
        alert(`Booking ID: ${booking.id}\nTable ID: ${booking.id_tables}\nReservation: ${booking.reservation}\nTime Reserve: ${booking.time_reserve}\nWho Booked: ${booking.who_booked}`);
      })
      .catch((error) => {
        alert(`Error: ${error.message}`);
        console.error("Error finding booking:", error);
      });
  });

  // Initial load
  loadBookings();
});

