<template>
	<div>
		<h2>Warranty Claims</h2>
		<div id="filter-container" class="filter-container">
			<button @click="addNewWarranty" id="add-warranty-button" class="interaction-button">
				Add New Warranty Claim
			</button>
		</div>
		<DataTable
			:data="tableData"
			:columns="columns"
			tableName="warranties"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			:onLazyLoad="handleLazyLoad"
			@lazy-load="handleLazyLoad"
		/>
	</div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import DataTable from "../common/DataTable.vue";
import Api from "../../api";
import { FilterMatchMode } from "@primevue/core";
import { useLoadingStore } from "../../stores/loading";
import { usePaginationStore } from "../../stores/pagination";
import { useFiltersStore } from "../../stores/filters";

const loadingStore = useLoadingStore();
const paginationStore = usePaginationStore();
const filtersStore = useFiltersStore();

const tableData = ref([]);
const totalRecords = ref(0);
const isLoading = ref(false);

const addNewWarranty = () => {
	// TODO: Open modal or navigate to create warranty form
	console.log("Add new warranty claim clicked");
	// In the future, this could open a modal or navigate to a form
	// For now, just log the action
};

const columns = [
	{
		label: "Warranty ID",
		fieldName: "warrantyId",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Customer",
		fieldName: "customer",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Service Address",
		fieldName: "serviceAddress",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Issue Description",
		fieldName: "issueDescription",
		type: "text",
		sortable: false,
		filterable: false,
	},
	{
		label: "Priority",
		fieldName: "priority",
		type: "status",
		sortable: true,
		filterable: false,
	},
	{
		label: "Status",
		fieldName: "status",
		type: "status",
		sortable: true,
		filterable: true,
	},
	{
		label: "Complaint Date",
		fieldName: "complaintDate",
		type: "date",
		sortable: true,
		filterable: false,
	},
	{
		label: "Raised By",
		fieldName: "complaintRaisedBy",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Territory",
		fieldName: "territory",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Warranty Status",
		fieldName: "warrantyStatus",
		type: "status",
		sortable: true,
		filterable: true,
	},
];

// Handle lazy loading events from DataTable
const handleLazyLoad = async (event) => {
	console.log("Warranties page - handling lazy load:", event);

	try {
		isLoading.value = true;

		// Get pagination parameters
		const paginationParams = {
			page: event.page || 0,
			pageSize: event.rows || 10,
			sortField: event.sortField,
			sortOrder: event.sortOrder,
		};

		// Get filters (convert PrimeVue format to API format)
		const filters = {};
		if (event.filters) {
			Object.keys(event.filters).forEach((key) => {
				if (key !== "global" && event.filters[key] && event.filters[key].value) {
					filters[key] = event.filters[key];
				}
			});
		}

		// Check cache first
		const cachedData = paginationStore.getCachedPage(
			"warranties",
			paginationParams.page,
			paginationParams.pageSize,
			paginationParams.sortField,
			paginationParams.sortOrder,
			filters,
		);

		if (cachedData) {
			// Use cached data
			tableData.value = cachedData.records;
			totalRecords.value = cachedData.totalRecords;
			paginationStore.setTotalRecords("warranties", cachedData.totalRecords);

			console.log("Loaded from cache:", {
				records: cachedData.records.length,
				total: cachedData.totalRecords,
				page: paginationParams.page + 1,
			});
			return;
		}

		console.log("Making API call with:", { paginationParams, filters });

		// Get sorting from store for proper API call
		const sorting = filtersStore.getTableSorting("warranties");

		// Use the new paginated API method
		const result = await Api.getPaginatedWarrantyData(paginationParams, filters, sorting);

		// Update local state
		tableData.value = result.data;
		totalRecords.value = result.pagination.total;

		// Update pagination store with new total
		paginationStore.setTotalRecords("warranties", result.pagination.total);

		// Cache the result
		paginationStore.setCachedPage(
			"warranties",
			paginationParams.page,
			paginationParams.pageSize,
			paginationParams.sortField,
			paginationParams.sortOrder,
			filters,
			{
				records: result.data,
				totalRecords: result.pagination.total,
			},
		);

		console.log("Loaded from API:", {
			records: result.data.length,
			total: result.pagination.total,
			page: paginationParams.page + 1,
		});
	} catch (error) {
		console.error("Error loading warranty data:", error);
		tableData.value = [];
		totalRecords.value = 0;
	} finally {
		isLoading.value = false;
	}
};

// Load initial data
onMounted(async () => {
	// Initialize pagination and filters
	paginationStore.initializeTablePagination("warranties", { rows: 10 });
	filtersStore.initializeTableFilters("warranties", columns);

	// Load first page
	const initialPagination = paginationStore.getTablePagination("warranties");
	const initialFilters = filtersStore.getTableFilters("warranties");

	await handleLazyLoad({
		page: initialPagination.page,
		rows: initialPagination.rows,
		first: initialPagination.first,
		sortField: initialPagination.sortField,
		sortOrder: initialPagination.sortOrder,
		filters: initialFilters,
	});
});
</script>

<style scoped>
.filter-container {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 1rem;
}

.interaction-button {
	background-color: #007bff;
	color: white;
	border: none;
	padding: 0.5rem 1rem;
	border-radius: 4px;
	cursor: pointer;
	font-size: 0.9rem;
}

.interaction-button:hover {
	background-color: #0056b3;
}
</style>
