<template>
	<div class= "job-page">
		<h2>{{ isNew ? 'Create Job' : 'View Job' }}</h2>
		<div  class="page-actions">
		</div>
		<div class="info-section">
			<div class="address-info">
				<Card>
					<template #header>
						<div class="widget-header">
							<h3>Address</h3>
						</div>
					</template>
					<template #content>
						<div class="widget-content">
							{{ job.jobAddress["fullAddress"] || "" }}
						</div>
					</template>
				</Card>
			</div>
			<div class="customer-info">
				<Card>
					<template #header>
						<div class="widget-header">
							<h3>Customer</h3>
						</div>
					</template>
					<template #content>
						<div class="widget-content">
							{{ job.customer || "" }}
						</div>
					</template>
				</Card>
			</div>
			<div class="job-info">
				<Card>
					<template #header>
						<div class="widget-header">
							<h3>Job Status</h3>
						</div>
					</template>
					<template #content>
						<div class="widget-content">
							Job is {{ job.status }}.
							<button
								class="sidebar-button"
								@click="createInvoiceForJob()"
							>
								Create Invoice
							</button>
						</div>
					</template>
				</Card>
			</div>
		</div>
		<div class="task-list">
			<DataTable
				:data="tableData"
				:columns="columns"
				:tableActions="tableActions"
				tableName="jobtasks"
				:lazy="true"
				:totalRecords="totalRecords"
				:loading="isLoading"
				@lazy-load="handleLazyLoad"
			/>
		</div>
	</div>
</template>

<script setup>
import Card from "../common/Card.vue";
import DataTable from "../common/DataTable.vue";
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import Api from "../../api";
import { useLoadingStore } from "../../stores/loading";
import { usePaginationStore } from "../../stores/pagination";
import { useFiltersStore } from "../../stores/filters";
import { useNotificationStore } from "../../stores/notifications-primevue";

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

const route = useRoute();

const jobIdQuery = computed(() => route.query.name || "");
const isNew = computed(() => route.query.new === "true");

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

const job = ref(null);
const taskList = ref(null);

const columns = [
	{ label: "Task", fieldName: "subject", type: "text" },
	{ label: "ID", fieldName: "id", type: "text", sortable: true, filterable: true },
	{ label: "Address", fieldname: "address", type: "text" },
	{ label: "Category", fieldName: "", type: "text", sortable: true, filterable: true },
	{ label: "Status", fieldName: "status", type: "status", sortable: true, filterable: true },
];

const statusOptions = ref([
	"Open",
	"Working",
	"Pending Review",
	"Overdue",
	"Completed",
	"Cancelled",
]);

const tableActions = computed(() => [
	{
		label: "Set Status",
		rowAction: true,
		type: "menu",
		menuItems: statusOptions.value.map((option) => ({
			label: option,
			command: async (rowData) => {
				console.log("Setting status for row:", rowData, "to:", option);
				try {
					await Api.setTaskStatus(rowData.id, option);

					// Find and update the row in the table data
					const rowIndex = tableData.value.findIndex((row) => row.id === rowData.id);
					if (rowIndex >= 0) {
						// Update reactively
						tableData.value[rowIndex].status = option;
						notifications.addSuccess(`Status updated to ${option}`);
					}
				} catch (error) {
					console.error("Error updating status:", error);
					notifications.addError("Failed to update status");
				}
			},
		})),
		layout: {
			priority: "menu",
		},
	},
]);

const createInvoiceForJob = async () => {
	console.log(job);
	await Api.createInvoiceForJob(job.value.name);
}

const handleLazyLoad = async (event) => {
	console.log("Task list on Job Page - handling lazy load:", event);
	try {
		isLoading.value = true;

		// Get sorting information from filters store first (needed for cache key)
		const sorting = filtersStore.getTableSorting("jobTasks");
		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 = {project: jobIdQuery.value};
		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("jobTasks");
		}

		// Check cache first
		const cachedData = paginationStore.getCachedPage(
			"jobTasks",
			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("jobTasks", 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.getPaginatedJobTaskDetails(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("jobTasks", result.pagination.total);

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

		// Cache the result
		paginationStore.setCachedPage(
			"jobTasks",
			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;
	}
};

onMounted(async () => {
	console.log("DEBUG: Query params:", route.query);

	try {
		const optionsResult = await Api.getTaskStatusOptions();
		if (optionsResult && optionsResult.length > 0) {
			statusOptions.value = optionsResult;
		}
	} catch (error) {
		console.error("Error loading task status options:", error);
	}

	if (jobIdQuery.value) {
		// Viewing existing Job
		try {
			job.value = await Api.getJob(jobIdQuery.value);
			//taskList.value = await Api.getJobTaskList(jobIdQuery.value);
			console.log("DEBUG: Loaded job:", job.value);
		} catch (error) {
			console.error("Error loading job from DB:", error);
		}
	}

	// Initialize pagination and filters
	paginationStore.initializeTablePagination("jobTasks", { rows: 10 });
	filtersStore.initializeTableFilters("jobTasks", columns);
	filtersStore.initializeTableSorting("jobsTasks");

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

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


});
</script>

<style scoped>
.info-section {
	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;*/
}
.job-page{
	height: 100%;
	margin: 20px;
	gap: 20px;
	background-color: transparent;
}
</style>
