<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>

		<div id="filter-container" class="filter-container">
			<button @click="onClick" id="add-customer-button" class="interaction-button">
				Add
			</button>
		</div>
		<DataTable
			:data="tableData"
			:columns="columns"
			:filters="filters"
			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";

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

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");
});

const onClick = () => {
	//frappe.new_doc("Customer");
	modalStore.openCreateClient();
};

// 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 = {
	addressTitle: { value: null, matchMode: FilterMatchMode.CONTAINS },
};

const columns = [
	{
		label: "Name",
		fieldName: "addressTitle",
		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 },
];
// Handle lazy loading events from DataTable
const handleLazyLoad = async (event) => {
	console.log("Clients page - handling lazy load:", event);

	try {
		isLoading.value = true;

		// Get sorting information from filters store first (needed for cache key)
		const sorting = filtersStore.getTableSorting("clients");

		// 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("clients");
		}

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

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

		// Cache the result
		paginationStore.setCachedPage(
			"clients",
			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 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 initialSorting = filtersStore.getTableSorting("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: initialSorting.field || initialPagination.sortField,
		sortOrder: initialSorting.order || initialPagination.sortOrder,
		filters: initialFilters,
	});
});
</script>
<style lang="css">
.page-container {
	height: 100%;
}

.chart-section {
	margin-bottom: 20px;
}

.filter-container {
	margin-bottom: 15px;
}

.interaction-button {
	background: #3b82f6;
	color: white;
	border: none;
	padding: 10px 20px;
	border-radius: 6px;
	cursor: pointer;
	font-size: 14px;
	font-weight: 500;
	transition: background 0.2s;
}

.interaction-button:hover {
	background: #2563eb;
}
</style>
