<template>
	<div class="page-container">
		<h2>Tasks</h2>
		<!-- Todo Chart Section -->
		<div class = "widgets-grid">
			<!-- Widget Cards go here if needed -->
		</div>
		<DataTable
			:data="tableData"
			:columns="columns"
			:filters="filters"
			:tableActions="tableActions"
			tableName="tasks"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			@lazy-load="handleLazyLoad"
		/>
	</div>
</template>
<script setup>
import DataTable from "../common/DataTable.vue";
import { ref, onMounted, watch, computed } 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 { useNotificationStore } from "../../stores/notifications-primevue";

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

const tableData = ref([]);
const totalRecords = ref(0);
const isLoading = ref(false);
const showCompleted = ref(false);
const statusOptions = ref([
	"Open",
	"Working",
	"Pending",
	"Review",
	"Overdue",
	"Completed",
	"Cancelled",
]);

// Computed property to get current filters for the chart
const currentFilters = computed(() => {
	return filtersStore.getTableFilters("tasks");
});

const columns = [
	{ label: "Task", fieldName: "subject", type: "text", sortable: true, filterable: true },
	{ label: "Job", fieldName: "project", type: "link", sortable: true,
		onLinkClick: (link, rowData) => handleProjectClick(link, rowData)
	},
	{ label: "Address", fieldName: "address", type: "link", sortable: true,
		onLinkClick: (link, rowData) => handlePropertyClick(link, rowData)
	},
	{ label: "Type", fieldName: "type", type: "text", sortable: true },
	{ label: "Overall Status", fieldName: "status", type: "status", sortable: true },
];

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

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

const tableActions = [
	{
		label: "Show Completed",
		action: () => {
			showCompleted = !showCompleted
			},
		type: "button",
		style: "info",
	},
	{
		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 {
					// Uncomment when API is ready
					// 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"
		},
	},
];

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

	try {
		isLoading.value = true;

		// If this is a sort event, update the store first
		if (event.sortField !== undefined && event.sortOrder !== undefined) {
			console.log("Sort event detected - updating store with:", {
				sortField: event.sortField,
				sortOrder: event.sortOrder,
				orderType: typeof event.sortOrder,
			});
			filtersStore.updateTableSorting("tasks", event.sortField, event.sortOrder);
		}

		// Get sorting information from filters store in backend format
		const sortingArray = filtersStore.getTableSortingForBackend("tasks");
		console.log("Current sorting array for backend:", sortingArray);

		// Get pagination parameters
		const paginationParams = {
			page: event.page || 0,
			pageSize: event.rows || 10,
		}; // 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];
				}
			});
		}

		// For cache key, use primary sort field/order for compatibility
		const primarySortField = filtersStore.getPrimarySortField("tasks") || event.sortField;
		const primarySortOrder = filtersStore.getPrimarySortOrder("tasks") || event.sortOrder;

		// Always fetch fresh data from API (cache only stores pagination/filter/sort state, not data)
		// Call API with pagination, filters, and sorting in backend format
		console.log("Making API call with:", {
			paginationParams,
			filters,
			sortingArray,
		});

		const result = await Api.getPaginatedTaskDetails(
			paginationParams,
			filters,
			sortingArray,
		);

		console.log("API response:", result);

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

		// Update pagination store with new total
		paginationStore.setTotalRecords("tasks", result.pagination.total);
	} catch (error) {
		console.error("Error loading task data:", error);
		// You could also show a toast or other error notification here
		tableData.value = [];
		totalRecords.value = 0;
	} finally {
		isLoading.value = false;
	}
};

const handleProjectClick = (link, rowData) => {
	console.log("DEBUG: Project Link Clicked.");
	const jobId = encodeURIComponent(rowData.project);
	router.push(`/job?jobId=${jobId}`);
};

const handlePropertyClick = (link, rowData) => {
	console.log("DEBUG: Property Link Clicked.");
	const client = encodeURIComponent(rowData.customerName);
	const address = encodeURIComponent(rowData.address);
	router.push(`/property?client=${client}&address=${address}`);
}


// If we implement a Task Detail View, this may be helpful
//const handleRowClick = (event) => {
//	const rowData = event.data;
//	router.push(`/task?taskId=${rowData.name}`);
//}

watch(showCompleted, () => {
	if (showCompleted) {
		// TODO: Logic for filtering on "Completed" goes here
	}
});

// Load initial data
onMounted(async () => {
	notifications.addWarning("Tasks page coming soon");
	// Initialize pagination and filters
	paginationStore.initializeTablePagination("tasks", { rows: 10 });
	filtersStore.initializeTableFilters("tasks", columns);
	filtersStore.initializeTableSorting("tasks");

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

	const optionsResult = await Api.getTaskStatusOptions();
	statusOptions.value = optionsResult;
	console.log("DEBUG: Loaded Status options: ", statusOptions.value)

	await handleLazyLoad({
		page: initialPagination.page,
		rows: initialPagination.rows,
		first: initialPagination.first,
		sortField: initialSorting.field || initialPagination.sortField,
		sortOrder: initialSorting.order || initialPagination.sortOrder,
		filters: initialFilters,
	});
});
</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>
