<template>
	<div class="page-container">
		<H2>Client Contact List</H2>

		<!-- Status Chart Section -->
		<div class="chart-section">
			<StatusChart
				:statusData="statusCounts"
				:onWeekChange="handleWeekChange"
				:loading="chartLoading"
			/>
		</div>

		<DataTable
			:data="tableData"
			:columns="columns"
			:filters="filters"
			:tableActions="tableActions"
			tableName="clients"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			@lazy-load="handleLazyLoad"
		/>
	</div>
</template>
<script setup>
import { onMounted, ref, watch, computed } from "vue";
import DataTable from "../common/DataTable.vue";
import StatusChart from "../common/StatusChart.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";
import { useModalStore } from "../../stores/modal";
import { useRouter } from "vue-router";

const loadingStore = useLoadingStore();
const paginationStore = usePaginationStore();
const filtersStore = useFiltersStore();
const modalStore = useModalStore();
const router = useRouter();

const tableData = ref([]);
const totalRecords = ref(0);
const isLoading = ref(false);
const statusCounts = ref({}); // Start with empty object
const currentWeekParams = ref({});
const chartLoading = ref(true); // Start with loading state

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

// Handle week change from chart
const handleWeekChange = async (weekParams) => {
	console.log("handleWeekChange called with:", weekParams);
	currentWeekParams.value = weekParams;
	await refreshStatusCounts();
};

// Refresh status counts with current week and filters
const refreshStatusCounts = async () => {
	chartLoading.value = true;
	try {
		let params = {};

		// Only apply weekly filtering if weekParams is provided (not null)
		if (currentWeekParams.value) {
			params = {
				weekly: true,
				weekStartDate: currentWeekParams.value.weekStartDate,
				weekEndDate: currentWeekParams.value.weekEndDate,
			};
			console.log("Using weekly filter:", params);
		} else {
			// No weekly filtering - get all time data
			params = {
				weekly: false,
			};
			console.log("Using all-time data (no weekly filter)");
		}

		// Add current filters to the params
		const currentFilters = filtersStore.getTableFilters("clients");
		if (currentFilters && Object.keys(currentFilters).length > 0) {
			params.filters = currentFilters;
		}

		const response = await Api.getClientStatusCounts(params);
		statusCounts.value = response || {};

		console.log("Status counts updated:", statusCounts.value);
	} catch (error) {
		console.error("Error refreshing status counts:", error);
		statusCounts.value = {};
	} finally {
		chartLoading.value = false;
	}
};

const filters = {
	customerName: { value: null, matchMode: FilterMatchMode.CONTAINS },
	address: { value: null, matchMode: FilterMatchMode.CONTAINS },
};

const columns = [
	{
		label: "Customer Name",
		fieldName: "customerName",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Address",
		fieldName: "address",
		type: "text",
		sortable: true,
		filterable: true,
	},
	{
		label: "Appt. Scheduled",
		fieldName: "appointmentScheduledStatus",
		type: "status",
		sortable: true,
	},
	{
		label: "Estimate Sent",
		fieldName: "estimateSentStatus",
		type: "status",
		sortable: true,
	},
	{
		label: "Payment Received",
		fieldName: "paymentReceivedStatus",
		type: "status",
		sortable: true,
	},
	{
		label: "Job Status",
		fieldName: "jobStatus",
		type: "status",
		sortable: true,
	},
];

const tableActions = [
	{
		label: "Add Client",
		action: () => {
			modalStore.openModal("createClient");
		},
		type: "button",
		style: "primary",
		icon: "pi pi-plus",
		layout: {
			position: "left",
			variant: "filled",
		},
		// Global action - always available
	},
	{
		label: "View Details",
		action: (rowData) => {
			router.push(`/clients/${rowData.customerName}`);
		},
		type: "button",
		style: "info",
		icon: "pi pi-eye",
		requiresSelection: true, // Single selection action - appears above table, enabled when exactly one row selected
		layout: {
			position: "center",
			variant: "outlined",
		},
	},
	// {
	// 	label: "Export Selected",
	// 	action: (selectedRows) => {
	// 		console.log("Exporting", selectedRows.length, "clients:", selectedRows);
	// 		// Implementation would export selected clients
	// 	},
	// 	type: "button",
	// 	style: "success",
	// 	icon: "pi pi-download",
	// 	requiresMultipleSelection: true, // Bulk action - operates on selected rows
	// 	layout: {
	// 		position: "right".,
	// 		variant: "filled",
	// 	},
	// },
	{
		label: "Edit",
		action: (rowData) => {
			console.log("Editing client:", rowData);
			// Implementation would open edit modal
		},
		type: "button",
		style: "secondary",
		icon: "pi pi-pencil",
		rowAction: true, // Row action - appears in each row's actions column
		layout: {
			priority: "primary",
			variant: "outlined",
		},
	},
	{
		label: "Quick View",
		action: (rowData) => {
			console.log("Quick view for:", rowData.addressTitle);
			// Implementation would show quick preview
		},
		type: "button",
		style: "info",
		icon: "pi pi-search",
		rowAction: true, // Row action - appears in each row's actions column
		layout: {
			priority: "secondary",
			variant: "compact",
		},
	},
];
// Handle lazy loading events from DataTable
const handleLazyLoad = async (event) => {
	console.log("Clients 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("clients", event.sortField, event.sortOrder);
		}

		// Get sorting information from filters store in backend format
		const sortingArray = filtersStore.getTableSortingForBackend("clients");
		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];
				}
			});
		}

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

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

		// Check cache first
		const cachedData = paginationStore.getCachedPage(
			"clients",
			paginationParams.page,
			paginationParams.pageSize,
			primarySortField,
			primarySortOrder,
			filters,
		);

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

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

		// Call API with pagination, filters, and sorting in backend format
		console.log("Making API call with:", {
			paginationParams,
			filters,
			sortingArray,
		});

		const result = await Api.getPaginatedClientDetails(
			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("clients", result.pagination.total);
		// Cache the result using primary sort for compatibility
		paginationStore.setCachedPage(
			"clients",
			paginationParams.page,
			paginationParams.pageSize,
			primarySortField,
			primarySortOrder,
			filters,
			{
				records: result.data,
				totalRecords: result.pagination.total,
			},
		);
	} catch (error) {
		console.error("Error loading client data:", error);
		// You could also show a toast or other error notification here
		tableData.value = [];
		totalRecords.value = 0;
	} finally {
		isLoading.value = false;
	}
};
// Watch for filters change to update status counts
watch(
	() => filtersStore.getTableFilters("clients"),
	async () => {
		await refreshStatusCounts();
	},
	{ deep: true },
);

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

	// Load first page
	const initialPagination = paginationStore.getTablePagination("clients");
	const initialFilters = filtersStore.getTableFilters("clients");
	const primarySortField = filtersStore.getPrimarySortField("clients");
	const primarySortOrder = filtersStore.getPrimarySortOrder("clients");

	// Don't load initial status counts here - let the chart component handle it
	// The chart will emit the initial week parameters and trigger refreshStatusCounts

	await handleLazyLoad({
		page: initialPagination.page,
		rows: initialPagination.rows,
		first: initialPagination.first,
		sortField: primarySortField || initialPagination.sortField,
		sortOrder: primarySortOrder || initialPagination.sortOrder,
		filters: initialFilters,
	});
});
</script>
<style lang="css">
.page-container {
	height: 100%;
}

.chart-section {
	margin-bottom: 20px;
}
</style>
