{{ define "content" }}
<div class="flex-1 flex flex-col overflow-hidden">
  <!-- Toolbar -->
  <div class="bg-gray-50 border-b border-gray-200 px-6 py-3">
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-4 text-sm">
        <div class="relative">
          <i
            class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm"
          ></i>
          <input
            type="text"
            placeholder="Search Addresses"
            class="w-full pl-8 pr-3 py-2 text-sm border border-gray-200 rounded bg-white"
          />
        </div>
      </div>
      {{if .Pagination}}
      <div class="flex items-center gap-4 text-sm">
        <div class="flex items-center gap-2">
          <label for="pageSize" class="text-gray-600">Per page:</label>
          <select
            id="pageSize"
            onchange="changePageSize(this.value)"
            class="px-3 py-1 text-sm border border-gray-200 rounded bg-white"
          >
            <option value="20" {{if eq .Pagination.PageSize 20}}selected{{end}}>
              20
            </option>
            <option value="50" {{if eq .Pagination.PageSize 50}}selected{{end}}>
              50
            </option>
            <option
              value="100"
              {{if
              eq
              .Pagination.PageSize
              100}}selected{{end}}
            >
              100
            </option>
          </select>
        </div>
        <div class="flex items-center gap-2">
          <button
            onclick="goToPage({{.Pagination.PreviousPage}})"
            {{if
            not
            .Pagination.HasPrevious}}disabled{{end}}
            class="px-3 py-1 text-sm border border-gray-200 rounded {{if .Pagination.HasPrevious}}hover:bg-gray-50 text-gray-700{{else}}text-gray-400 cursor-not-allowed{{end}}"
          >
            <i class="fas fa-chevron-left"></i>
          </button>
          <span class="px-2 text-gray-600"
            >{{.Pagination.CurrentPage}} / {{.Pagination.TotalPages}}</span
          >
          <button
            onclick="goToPage({{.Pagination.NextPage}})"
            {{if
            not
            .Pagination.HasNext}}disabled{{end}}
            class="px-3 py-1 text-sm border border-gray-200 rounded {{if .Pagination.HasNext}}hover:bg-gray-50 text-gray-700{{else}}text-gray-400 cursor-not-allowed{{end}}"
          >
            <i class="fas fa-chevron-right"></i>
          </button>
        </div>
      </div>
      {{end}}
    </div>
  </div>

  <!-- Table -->
  <div
    class="flex-1 overflow-x-auto overflow-y-auto bg-white border border-gray-100"
  >
    <table class="w-full divide-gray-200 text-sm table-auto">
      <thead class="bg-gray-50 divide-gray-200 sticky top-0">
        <tr
          class="text-left text-gray-700 font-medium border-b border-gray-200"
        >
          <th class="px-6 py-3 whitespace-nowrap">Validated</th>
          <th class="px-6 py-3 whitespace-nowrap">Address</th>
          <th class="px-6 py-3 whitespace-nowrap">Coordinates</th>
          <th class="px-6 py-3 whitespace-nowrap">Assigned User</th>
          <th class="px-6 py-3 whitespace-nowrap">Appointment</th>
          <th class="px-6 py-3 whitespace-nowrap">Assign</th>
          <th class="px-6 py-3 whitespace-nowrap">Remove</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-200">
        {{ range .Addresses }}
        <tr class="hover:bg-gray-50">
          <td class="px-6 py-3 whitespace-nowrap">
            {{ if .VisitedValidated }}
            <span
              class="inline-flex items-center px-2 py-1 text-xs font-medium bg-green-100 text-green-700 rounded-full"
            >
              <i class="fas fa-check mr-1"></i> Valid
            </span>
            {{ else }}
            <span
              class="inline-flex items-center px-2 py-1 text-xs font-medium bg-red-100 text-red-700 rounded-full"
            >
              <i class="fas fa-times mr-1"></i> Invalid
            </span>
            {{ end }}
          </td>
          <td class="px-6 py-3 whitespace-nowrap">{{ .Address }}</td>
          <td class="px-6 py-3 whitespace-nowrap">
            <a
              href="https://www.google.com/maps/search/?api=1&query={{ .Latitude }},{{ .Longitude }}"
              target="_blank"
              class="text-blue-600 hover:underline"
            >
              ({{ .Latitude }}, {{ .Longitude }})
            </a>
          </td>
          <td class="px-6 py-3 whitespace-nowrap">
            {{ if .UserName }}{{ .UserName }}<br /><span
              class="text-xs text-gray-500"
              >{{ .UserEmail }}</span
            >{{ else }}<span class="text-gray-400">Unassigned</span>{{ end }}
          </td>
          <td class="px-6 py-3 whitespace-nowrap">
            {{ if .AppointmentDate }} {{ .AppointmentDate }} {{ .AppointmentTime
            }} {{ else }}
            <span class="text-gray-400">No appointment</span>
            {{ end }}
          </td>
          <td class="px-6 py-3 whitespace-nowrap">
            {{ if .Assigned }}
            <button
              class="px-3 py-1 bg-gray-400 text-white text-sm cursor-not-allowed"
              disabled
            >
              Assigned
            </button>
            {{ else }}
            <button
              class="px-3 py-1 bg-blue-600 text-white text-sm hover:bg-blue-700"
              onclick="openAssignModal({{ .AddressID }}, '{{ .Address }}')"
            >
              Assign
            </button>
            {{ end }}
          </td>
          <td class="px-6 py-3 whitespace-nowrap">
            {{ if .Assigned }}
            <form
              action="/remove_assigned_address"
              method="POST"
              class="inline-block"
            >
              <input type="hidden" name="address_id" value="{{ .AddressID }}" />
              <input type="hidden" name="user_id" value="{{ .UserID }}" />
              <button
                type="submit"
                class="text-red-600 hover:text-red-800 font-medium text-xs px-2 py-1 hover:bg-red-50 transition-colors"
              >
                Delete
              </button>
            </form>
            {{ else }}
            <span class="text-gray-400 text-xs">-</span>
            {{ end }}
          </td>
        </tr>
        {{ else }}
        <tr>
          <td colspan="7" class="px-6 py-8 text-center text-gray-500">
            No addresses found
          </td>
        </tr>
        {{ end }}
      </tbody>
    </table>
  </div>

  <!-- Assign Modal -->
  <div
    id="assignModal"
    class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50"
  >
    <div class="bg-white w-full max-w-lg mx-4 shadow-lg">
      <!-- Modal Header -->
      <div
        class="flex justify-between items-center px-6 py-4 border-b border-gray-200"
      >
        <h2 class="text-lg font-semibold text-gray-900">Assign Address</h2>
        <button
          onclick="closeAssignModal()"
          class="text-gray-400 hover:text-gray-600 focus:outline-none"
        >
          <i class="fas fa-times text-xl"></i>
        </button>
      </div>

      <!-- Modal Body -->
      <form
        id="assignForm"
        method="POST"
        action="/assign_address"
        class="p-6 space-y-4"
      >
        <input type="hidden" name="address_id" id="modalAddressID" />

        <!-- Selected Address Display -->
        <div class="bg-gray-50 p-3 border border-gray-200">
          <div class="flex items-center space-x-2 mb-4">
            <i class="fas fa-map-marker-alt text-gray-500"></i>
            <span class="font-medium text-gray-900">Selected Address:</span>
          </div>
          <div class="text-sm text-gray-700 mb-4" id="selected-address">
            None selected
          </div>

          <!-- User Selection -->
          <div class="mb-4">
            <label
              for="user_id"
              class="block text-sm font-medium text-gray-700 mb-2"
            >
              <i class="fas fa-user mr-2"></i>Select User
            </label>
            <select
              name="user_id"
              id="user_id"
              class="w-full px-3 py-2 border border-gray-300 bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
              required
            >
              <option value="">-- Select User --</option>
              {{ range .Users }}
              <option value="{{ .ID }}">{{ .Name }}</option>
              {{ end }}
            </select>
          </div>

          <!-- Date Selection -->
          <div class="mb-4">
            <label
              for="appointment-date"
              class="block text-sm font-medium text-gray-700 mb-2"
            >
              <i class="fas fa-calendar mr-2"></i>Appointment Date
            </label>
            <input
              type="date"
              id="appointment-date"
              name="appointment_date"
              required
              class="w-full px-3 py-2 border border-gray-300 bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
              min=""
            />
          </div>

          <!-- Time Selection -->
          <div class="grid grid-cols-2 gap-4">
            <!-- Start Time -->
            <div>
              <label
                for="time"
                class="block text-sm font-medium text-gray-700 mb-2"
              >
                <i class="fas fa-clock mr-2"></i>Time
              </label>
              <select
                id="time"
                name="time"
                required
                onchange="updateEndTime()"
                class="w-full px-3 py-2 border border-gray-300 bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">Select Time</option>
              </select>
            </div>
          </div>
        </div>

        <!-- Modal Actions -->
        <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
          <button
            type="button"
            onclick="closeAssignModal()"
            class="px-4 py-2 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium"
          >
            Cancel
          </button>
          <button
            type="submit"
            class="px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium"
          >
            <i class="fas fa-check mr-2"></i> Assign
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<style>
  /* Square corners across UI */
  * {
    border-radius: 0 !important;
  }

  input,
  select,
  button {
    transition: all 0.2s ease;
  }

  button {
    font-weight: 500;
    letter-spacing: 0.025em;
  }
</style>

<script>
  // Generate time options in 10-minute increments
  function generateTimeOptions() {
    const times = [];
    for (let hour = 0; hour < 24; hour++) {
      for (let minute = 0; minute < 60; minute += 20) {
        const timeString =
          String(hour).padStart(2, "0") + ":" + String(minute).padStart(2, "0");
        const displayTime = formatTime12Hour(hour, minute);
        times.push({ value: timeString, display: displayTime });
      }
    }
    return times;
  }

  // Format time to 12-hour format
  function formatTime12Hour(hour, minute) {
    const ampm = hour >= 12 ? "PM" : "AM";
    const displayHour = hour % 12 || 12;
    return displayHour + ":" + String(minute).padStart(2, "0") + " " + ampm;
  }

  // Populate time dropdown
  function populateTimeSelect() {
    const timeSelect = document.getElementById("time");
    const times = generateTimeOptions();

    timeSelect.innerHTML = '<option value="">Select Time</option>';
    times.forEach((time) => {
      const option = new Option(time.display, time.value);
      timeSelect.appendChild(option);
    });
  }

  function openAssignModal(addressID, address) {
    document.getElementById("modalAddressID").value = addressID;
    document.getElementById("selected-address").textContent =
      address || "Address ID: " + addressID;

    // Set minimum date to today
    const today = new Date().toISOString().split("T")[0];
    document.getElementById("appointment-date").min = today;
    document.getElementById("appointment-date").value = today;

    document.getElementById("assignModal").classList.remove("hidden");
    document.getElementById("assignModal").classList.add("flex");
  }

  function closeAssignModal() {
    document.getElementById("assignModal").classList.remove("flex");
    document.getElementById("assignModal").classList.add("hidden");
    document.getElementById("assignForm").reset();
    document.getElementById("selected-address").textContent = "None selected";
  }

  function goToPage(page) {
    var urlParams = new URLSearchParams(window.location.search);
    urlParams.set("page", page);
    window.location.search = urlParams.toString();
  }

  function changePageSize(pageSize) {
    var urlParams = new URLSearchParams(window.location.search);
    urlParams.set("pageSize", pageSize);
    urlParams.set("page", 1);
    window.location.search = urlParams.toString();
  }

  // Initialize when page loads
  document.addEventListener("DOMContentLoaded", function () {
    populateTimeSelect();

    // Close modal when clicking outside
    document
      .getElementById("assignModal")
      .addEventListener("click", function (e) {
        if (e.target === this) {
          closeAssignModal();
        }
      });
  });
</script>

{{ end }}
