let serviceTemplates = [];
let serviceTypes = [];
let currentPage = 1;
const itemsPerPage = 10;

// Load service templates and types on page load
document.addEventListener("DOMContentLoaded", () => {
	loadServiceTypes();
	loadServiceTemplates();
	setupEventListeners();
});

function setupEventListeners() {
	document
		.getElementById("searchInput")
		.addEventListener("input", filterServices);
	document
		.getElementById("statusFilter")
		.addEventListener("change", filterServices);
	document
		.getElementById("typeFilter")
		.addEventListener("change", filterServices);
	document
		.getElementById("isRecurring")
		.addEventListener("change", toggleRecurrenceFields);
	document
		.getElementById("recurrencePattern")
		.addEventListener("change", handleRecurrencePatternChange);
}

async function loadServiceTypes() {
	try {
		const response = await apiRequest(API_ENDPOINTS.SERVICE_TYPES);
		if (response.success) {
			serviceTypes = response.data.service_types || [];
			populateServiceTypeDropdown();
		}
	} catch (error) {
		console.error("Error loading service types:", error);
	}
}

function populateServiceTypeDropdown() {
	const select = document.getElementById("serviceType");
	select.innerHTML = '<option value="">Select Type</option>';
	serviceTypes.forEach((type) => {
		const option = document.createElement("option");
		option.value = type.id;
		option.textContent = type.name;
		select.appendChild(option);
	});
}

function toggleRecurrenceFields() {
	const isRecurring = document.getElementById("isRecurring").checked;
	const recurrenceFields = document.getElementById("recurrenceFields");
	if (isRecurring) {
		recurrenceFields.classList.remove("hidden");
	} else {
		recurrenceFields.classList.add("hidden");
	}
}

function handleRecurrencePatternChange() {
	const pattern = document.getElementById("recurrencePattern").value;
	const daysField = document.getElementById("recurrenceDaysField");

	if (pattern === "weekly") {
		daysField.style.display = "block";
	} else {
		daysField.style.display = "none";
	}
}

async function loadServiceTemplates() {
	try {
		const response = await apiRequest(API_ENDPOINTS.SERVICE_TEMPLATES);
		if (response.success) {
			serviceTemplates = response.data.templates || [];
			renderServices();
		} else {
			showMessage("Failed to load service templates");
		}
	} catch (error) {
		console.error("Error loading service templates:", error);
		showMessage("Failed to load service templates");
	}
}

function filterServices() {
	const searchTerm = document.getElementById("searchInput").value.toLowerCase();
	const statusFilter = document.getElementById("statusFilter").value;
	const typeFilter = document.getElementById("typeFilter").value;

	const filtered = serviceTemplates.filter((template) => {
		const matchesSearch =
			template.name.toLowerCase().includes(searchTerm) ||
			(template.location &&
				template.location.toLowerCase().includes(searchTerm));

		const matchesStatus =
			!statusFilter ||
			(statusFilter === "active" && template.is_active) ||
			(statusFilter === "inactive" && !template.is_active);

		const matchesType =
			!typeFilter ||
			(typeFilter === "recurring" && template.is_recurring) ||
			(typeFilter === "one-time" && !template.is_recurring);

		return matchesSearch && matchesStatus && matchesType;
	});

	renderServices(filtered);
}

function renderServices(templatesToRender = serviceTemplates) {
	const tbody = document.getElementById("servicesTableBody");

	if (templatesToRender.length === 0) {
		tbody.innerHTML = `
            <tr>
                <td colspan="6" style="text-align: center; padding: 40px; color: #888;">
                    No service templates found
                </td>
            </tr>
        `;
		return;
	}

	const start = (currentPage - 1) * itemsPerPage;
	const end = start + itemsPerPage;
	const paginatedTemplates = templatesToRender.slice(start, end);

	tbody.innerHTML = paginatedTemplates
		.map(
			(template) => `
        <tr>
            <td>
                <div style="font-weight: 600;">${template.name}</div>
                ${
									template.description
										? `<div style="font-size: 12px; color: #888; margin-top: 4px;">${template.description}</div>`
										: ""
								}
            </td>
            <td>
                <span class="badge" style="background: rgba(234, 179, 8, 0.1); color: #eab308;">
                    ${template.service_type_name || "N/A"}
                </span>
            </td>
            <td>
                ${
									template.is_recurring
										? `<span class="badge info">${
												template.recurrence_pattern || "Weekly"
										  }</span>`
										: '<span class="badge" style="background: rgba(128,128,128,0.1); color: #888;">One-Time</span>'
								}
            </td>
            <td>${template.location || "N/A"}</td>
            <td>${
							template.is_active
								? '<span class="badge success">Active</span>'
								: '<span class="badge" style="background: rgba(128,128,128,0.1); color: #888;">Inactive</span>'
						}</td>
            <td>
                <div class="action-buttons">
                    <button class="btn-icon" onclick="activateService(${
											template.id
										})" title="Activate Service" style="background: #eab308; color: white;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"></circle>
                            <polyline points="12 6 12 12 16 14"></polyline>
                        </svg>
                    </button>
                    <button class="btn-icon" onclick="editService(${
											template.id
										})" title="Edit">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                        </svg>
                    </button>
                    <button class="btn-icon danger" onclick="deleteService(${
											template.id
										})" title="Delete">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="3 6 5 6 21 6"></polyline>
                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                        </svg>
                    </button>
                </div>
            </td>
        </tr>
    `
		)
		.join("");

	renderPagination(templatesToRender.length);
}

function renderPagination(totalItems) {
	const totalPages = Math.ceil(totalItems / itemsPerPage);
	const pagination = document.getElementById("pagination");

	if (totalPages <= 1) {
		pagination.innerHTML = "";
		return;
	}

	let html = `
        <button onclick="changePage(${currentPage - 1})" ${
		currentPage === 1 ? "disabled" : ""
	}>Previous</button>
    `;

	for (let i = 1; i <= totalPages; i++) {
		html += `<button onclick="changePage(${i})" ${
			i === currentPage ? 'class="active"' : ""
		}>${i}</button>`;
	}

	html += `
        <button onclick="changePage(${currentPage + 1})" ${
		currentPage === totalPages ? "disabled" : ""
	}>Next</button>
    `;

	pagination.innerHTML = html;
}

function changePage(page) {
	const totalPages = Math.ceil(serviceTemplates.length / itemsPerPage);
	if (page < 1 || page > totalPages) return;
	currentPage = page;
	renderServices();
}

function openCreateModal() {
	document.getElementById("modalTitle").textContent = "Create Service Template";
	document.getElementById("serviceForm").reset();
	document.getElementById("serviceId").value = "";
	document.getElementById("recurrenceFields").classList.add("hidden");
	document.getElementById("serviceModal").classList.remove("hidden");
}

function closeServiceModal() {
	document.getElementById("serviceModal").classList.add("hidden");
}

function activateService(templateId) {
	const template = serviceTemplates.find((t) => t.id === templateId);
	if (!template) return;

	document.getElementById("activateTemplateId").value = template.id;
	document.getElementById("activateTemplateName").value = template.name;

	// Pre-fill with default times if available
	if (template.default_start_time) {
		document.getElementById("occurrenceStartTime").value =
			template.default_start_time;
	}
	if (template.default_end_time) {
		document.getElementById("occurrenceEndTime").value =
			template.default_end_time;
	}

	// Set default date to today
	const today = new Date().toISOString().split("T")[0];
	document.getElementById("occurrenceDate").value = today;

	document.getElementById("activateModal").classList.remove("hidden");
}

function closeActivateModal() {
	document.getElementById("activateModal").classList.add("hidden");
	document.getElementById("activateForm").reset();
}

async function confirmActivation() {
	const templateId = document.getElementById("activateTemplateId").value;
	const occurrenceDate = document.getElementById("occurrenceDate").value;
	const startTime = document.getElementById("occurrenceStartTime").value;
	const endTime = document.getElementById("occurrenceEndTime").value;
	const notes = document.getElementById("occurrenceNotes").value;

	if (!occurrenceDate || !startTime || !endTime) {
		showMessage("Please fill in all required fields");
		return;
	}

	const formData = {
		service_template_id: Number.parseInt(templateId),
		occurrence_date: occurrenceDate,
		start_time: `${occurrenceDate} ${startTime}:00`,
		end_time: `${occurrenceDate} ${endTime}:00`,
		notes: notes,
	};

	try {
		const response = await apiRequest(API_ENDPOINTS.SERVICE_OCCURRENCES, {
			method: "POST",
			body: JSON.stringify(formData),
		});

		if (response.success) {
			showMessage("Service activated successfully");
			closeActivateModal();
		} else {
			showMessage(response.message || "Failed to activate service");
		}
	} catch (error) {
		console.error("Error activating service:", error);
		showMessage("Failed to activate service");
	}
}

async function editService(id) {
	const template = serviceTemplates.find((t) => t.id === id);
	if (!template) return;

	document.getElementById("modalTitle").textContent = "Edit Service Template";
	document.getElementById("serviceId").value = template.id;
	document.getElementById("serviceName").value = template.name;
	document.getElementById("serviceDescription").value =
		template.description || "";
	document.getElementById("serviceType").value = template.service_type_id || "";
	document.getElementById("serviceLocation").value = template.location || "";
	document.getElementById("serviceLatitude").value = template.latitude || "";
	document.getElementById("serviceLongitude").value = template.longitude || "";
	document.getElementById("serviceRadius").value =
		template.geofence_radius || 100;
	document.getElementById("isRecurring").checked = template.is_recurring;

	if (template.is_recurring) {
		document.getElementById("recurrencePattern").value =
			template.recurrence_pattern || "weekly";
		document.getElementById("recurrenceInterval").value =
			template.recurrence_interval || 1;
		document.getElementById("defaultStartTime").value =
			template.default_start_time || "";
		document.getElementById("defaultEndTime").value =
			template.default_end_time || "";
		document.getElementById("recurrenceStartDate").value =
			template.recurrence_start_date || "";
		document.getElementById("recurrenceEndDate").value =
			template.recurrence_end_date || "";

		// Set recurrence days if weekly
		if (template.recurrence_days) {
			const days = template.recurrence_days.split(",");
			document
				.querySelectorAll('input[name="recurrenceDays"]')
				.forEach((checkbox) => {
					checkbox.checked = days.includes(checkbox.value);
				});
		}
	}

	toggleRecurrenceFields();
	handleRecurrencePatternChange();
	document.getElementById("serviceModal").classList.remove("hidden");
}

async function saveService() {
	const serviceId = document.getElementById("serviceId").value;
	const isRecurring = document.getElementById("isRecurring").checked;

	const formData = {
		name: document.getElementById("serviceName").value,
		description: document.getElementById("serviceDescription").value,
		service_type_id: Number.parseInt(
			document.getElementById("serviceType").value
		),
		location: document.getElementById("serviceLocation").value,
		latitude: Number.parseFloat(
			document.getElementById("serviceLatitude").value
		),
		longitude: Number.parseFloat(
			document.getElementById("serviceLongitude").value
		),
		geofence_radius: Number.parseInt(
			document.getElementById("serviceRadius").value
		),
		is_recurring: isRecurring,
	};

	if (isRecurring) {
		formData.recurrence_pattern =
			document.getElementById("recurrencePattern").value;
		formData.recurrence_interval = Number.parseInt(
			document.getElementById("recurrenceInterval").value
		);
		formData.default_start_time =
			document.getElementById("defaultStartTime").value;
		formData.default_end_time = document.getElementById("defaultEndTime").value;
		formData.recurrence_start_date = document.getElementById(
			"recurrenceStartDate"
		).value;
		formData.recurrence_end_date =
			document.getElementById("recurrenceEndDate").value;

		// Get selected days for weekly recurrence
		if (formData.recurrence_pattern === "weekly") {
			const selectedDays = Array.from(
				document.querySelectorAll('input[name="recurrenceDays"]:checked')
			).map((cb) => cb.value);
			formData.recurrence_days = selectedDays.join(",");
		}
	}

	if (serviceId) {
		formData.id = Number.parseInt(serviceId);
	}

	try {
		const response = await apiRequest(API_ENDPOINTS.SERVICE_TEMPLATES, {
			method: "POST",
			body: JSON.stringify(formData),
		});

		if (response.success) {
			showMessage(
				serviceId
					? "Service template updated successfully"
					: "Service template created successfully"
			);
			closeServiceModal();
			loadServiceTemplates();
		} else {
			showMessage(response.message || "Failed to save service template");
		}
	} catch (error) {
		console.error("Error saving service template:", error);
		showMessage("Failed to save service template");
	}
}

async function deleteService(id) {
	if (
		!confirm(
			"Are you sure you want to delete this service template? This action cannot be undone."
		)
	) {
		return;
	}

	try {
		const response = await apiRequest(
			`${API_ENDPOINTS.SERVICE_TEMPLATES}?id=${id}`,
			{
				method: "DELETE",
			}
		);

		if (response.success) {
			showMessage("Service template deleted successfully");
			loadServiceTemplates();
		} else {
			showMessage(response.message || "Failed to delete service template");
		}
	} catch (error) {
		console.error("Error deleting service template:", error);
		showMessage("Failed to delete service template");
	}
}

function toggleSidebar() {
	document.getElementById("sidebar").classList.toggle("open");
}

function handleLogout() {
	localStorage.removeItem("admin_token");
	window.location.href = "login.html";
}

function showSuccess(message) {
	showMessage(message);
}

function showError(message) {
	showMessage(message, "error");
}
