<template>
	<div class="page-container">
		<h2>Jobs</h2>
		<!-- Todo Chart Section -->
		<div class = "widgets-grid">
			<!-- Jobs in Queue Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<Hammer class="widget-icon" />
						<h3>Jobs In Queue</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Jobs In Queue"
								:categories="chartData.jobsInQueue"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="filterBy('in queue')">
							View Queued Jobs
						</button>
					</div>
				</template>
			</Card>
			<!-- Jobs In Progress Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<Hammer class="widget-icon" />
						<h3>Jobs In Progress</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Jobs in Progress"
								:categories="chartData.jobsInProgress"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="filterBy('in progress')">
							View Jobs In Progress
						</button>
					</div>
				</template>
			</Card>
			<!-- Late Jobs Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<Alarm class="widget-icon" />
						<h3>Late Jobs</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Late Jobs"
								:categories="chartData.jobsLate"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="filterBy('late')">
							View Late Jobs
						</button>
					</div>
				</template>
			</Card>
			<!-- Ready to Invoice Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<CalendarCheck class="widget-icon" />
						<h3>Ready To Invoice</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Ready To Invoice"
								:categories="chartData.jobsToInvoice"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="navigateTo('/invoices')">
							View Ready To Invoice
						</button>
					</div>
				</template>
			</Card>
		</div>
		<DataTable
			:data="tableData"
			:columns="columns"
			tableName="jobs"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			@lazy-load="handleLazyLoad"
			@row-click="handleRowClick"
		/>
	</div>
</template>
<script setup>
import Card from "../common/Card.vue";
import DataTable from "../common/DataTable.vue";
import TodoChart from "../common/TodoChart.vue";
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import Api from "../../api";
import { useLoadingStore } from "../../stores/loading";
import { usePaginationStore } from "../../stores/pagination";
import { useFiltersStore } from "../../stores/filters";
import { useCompanyStore } from "../../stores/company.js";
import { useNotificationStore } from "../../stores/notifications-primevue";
import { Alarm, CalendarCheck, Hammer } from "@iconoir/vue";

const loadingStore = useLoadingStore();
const paginationStore = usePaginationStore();
const filtersStore = useFiltersStore();
const companyStore = useCompanyStore();
const notifications = useNotificationStore();

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

const chartData = ref({
	jobsInQueue: {labels: ["Queued"], data: [0], colors: ['blue']},
	jobsInProgress: {labels: ["In Progress"], data: [0], colors: ['blue']},
	jobsLate: {labels: ["Late"], data: [0], colors: ['red']},
	jobsToInvoice: {labels: ["Ready To Invoice"], data: [0], colors: ['green']},
})

const columns = [
	{ label: "Customer", fieldName: "customer", type: "text", sortable: true, filterable: true },
	{ label: "Address", fieldName: "jobAddress", type: "text", sortable: true },
	{ label: "Job ID", fieldName: "name", type: "text", sortable: true, filterable: true },
	{ label: "Overall Status", fieldName: "status", type: "status", sortable: true },
	{ label: "Invoice Status", fieldName: "invoiceStatus", type: "text", sortable: true },
	{ label: "Progress", fieldName: "percentComplete", type: "text", sortable: true }
];

const router = useRouter();
const navigateTo = (path) => {
	router.push(path);
};

const filterBy = (filter) => {
	console.log("DEBUG: Jobs filterBy not implemented yet.");
};

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

	try {
		isLoading.value = true;

		// Get sorting information from filters store first (needed for cache key)
		const sorting = filtersStore.getTableSorting("jobs");
		console.log("Current sorting state:", sorting);

		// 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];
				}
			});
		}

		// Clear cache when filters or sorting are active to ensure fresh data
		const hasActiveFilters = Object.keys(filters).length > 0;
		const hasActiveSorting = paginationParams.sortField && paginationParams.sortOrder;
		if (hasActiveFilters || hasActiveSorting) {
			paginationStore.clearTableCache("jobs");
		}

		// Check cache first
		const cachedData = paginationStore.getCachedPage(
			"jobs",
			paginationParams.page,
			paginationParams.pageSize,
			sorting.field || paginationParams.sortField,
			sorting.order || paginationParams.sortOrder,
			filters,
		);

		if (cachedData) {
			// Use cached data
			tableData.value = cachedData.records;
			totalRecords.value = cachedData.totalRecords;
			paginationStore.setTotalRecords("jobs", 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 });

		// Call API with pagination, filters, and sorting
		const result = await Api.getPaginatedJobDetails(paginationParams, filters, sorting);

		// Update local state - extract from pagination structure
		tableData.value = result.data;
		totalRecords.value = result.pagination.total;

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

		console.log("Updated pagination state:", {
			tableData: tableData.value.length,
			totalRecords: totalRecords.value,
			storeTotal: paginationStore.getTablePagination("jobs").totalRecords,
			storeTotalPages: paginationStore.getTotalPages("jobs"),
		});

		// Cache the result
		paginationStore.setCachedPage(
			"jobs",
			paginationParams.page,
			paginationParams.pageSize,
			sorting.field || paginationParams.sortField,
			sorting.order || 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 job data:", error);
		// You could also show a toast or other error notification here
		tableData.value = [];
		totalRecords.value = 0;
	} finally {
		isLoading.value = false;
	}
};

const handleRowClick = (event) => {
	const rowData = event.data;
	router.push(`/job?name=${rowData.name}`);
}

const loadChartData = async () => {
	chartData.value.jobsInQueue.data = await Api.getJobsInQueueCount(companyStore.currentCompany);
	chartData.value.jobsInProgress.data = await Api.getJobsInProgressCount(companyStore.currentCompany);
	chartData.value.jobsLate.data = await Api.getJobsLateCount(companyStore.currentCompany);
	chartData.value.jobsToInvoice.data = await Api.getJobsToInvoiceCount(companyStore.currentCompany);
}

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

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

	await handleLazyLoad({
		page: initialPagination.page,
		rows: initialPagination.rows,
		first: initialPagination.first,
		sortField: initialSorting.field || initialPagination.sortField,
		sortOrder: initialSorting.order || initialPagination.sortOrder,
	});

	// Chart Data
	await loadChartData();

});

watch(() => companyStore.currentCompany, async (newCompany, oldCompany) => {
	await loadChartData();
});

</script>
<style lang="css">
.widgets-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 20px;
	margin-bottom: 20px;
}
.widget-header {
	display: flex;
	align-items: center;
	gap: 10px;
	padding: 20px 20px 0;
}

.widget-icon {
	color: var(--theme-primary-strong);
	width: 24px;
	height: 24px;
}

.widget-header h3 {
	margin: 0;
	color: #2c3e50;
	font-size: 1.2rem;
}

.widget-content {
	display: flex;
	flex-direction: column;
	margin: 0;
	width: 200px;
	align-items: center;
	padding: 20px 20px 20px;
	/*gap: 15px;*/
}
.page-container {
	height: 100%;
	margin: 20px;
	gap: 20px;
	background-color: transparent;
}
</style>
