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

		<DataTable
			:data="tableData"
			:columns="columns"
			:filters="filters"
			:tableActions="tableActions"
			tableName="clients"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			@lazy-load="handleLazyLoad"
			@row-click="handleRowClick"
		/>
	</div>
</template>
<script setup>
import { onMounted, ref, watch, computed } from "vue";
import Card from "../common/Card.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, useRoute } from "vue-router";
import { useNotificationStore } from "../../stores/notifications-primevue";
import TodoChart from "../common/TodoChart.vue";
import { Calendar, Community, Hammer, PathArrowSolid, Clock, Shield, ShieldSearch,
ClipboardCheck, DoubleCheck, CreditCard, CardNoAccess, ChatBubbleQuestion, Edit,
WateringSoil, Soil, Truck, SoilAlt } from "@iconoir/vue";

const notifications = useNotificationStore();
const loadingStore = useLoadingStore();
const paginationStore = usePaginationStore();
const filtersStore = useFiltersStore();
const modalStore = useModalStore();
const router = useRouter();
const route = useRoute();

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

const lookup = route.query.lookup;

// 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,
		filterInputId: "customerSearchInput",
	},
	{
		label: "Type",
		fieldName: "clientType",
		type: "text",
		sortable: true,
	},
	{
		label: "Property",
		fieldName: "address",
		type: "text",
		sortable: true,
		filterable: true,
		filterInputId: "propertySearchInput",
	},
	//{
	//	label: "Create Estimate",
	//	fieldName: "createEstimate",
	//	type: "status-button",
	//	buttonVariant: "outlined",
	//	onStatusClick: (status, rowData) => handleEstimateClick(status, rowData),
	//},
	//{
	//	label: "Appt. Scheduled",
	//	fieldName: "appointmentScheduledStatus",
	//	type: "status-button",
	//	sortable: true,
	//	buttonVariant: "outlined",
	//	onStatusClick: (status, rowData) => handleAppointmentClick(status, rowData),
	//	// disableCondition: (status) => status?.toLowerCase() !== "not started",
	//},
	//{
	//	label: "Estimate Sent",
	//	fieldName: "estimateSentStatus",
	//	type: "status-button",
	//	sortable: true,
	//	buttonVariant: "outlined",
	//	onStatusClick: (status, rowData) => handleEstimateClick(status, rowData),
	//	// disableCondition: (status) => status?.toLowerCase() !== "not started",
	//},
	//{
	//	label: "Payment Received",
	//	fieldName: "paymentReceivedStatus",
	//	type: "status-button",
	//	sortable: true,
	//	buttonVariant: "outlined",
	//	onStatusClick: (status, rowData) => handlePaymentClick(status, rowData),
	//	// disableCondition: (status) => status?.toLowerCase() !== "not started",
	//},
	//{
	//	label: "Job Status",
	//	fieldName: "jobStatus",
	//	type: "status-button",
	//	sortable: true,
	//	buttonVariant: "outlined",
	//	onStatusClick: (status, rowData) => handleJobClick(status, rowData),
	//	// disableCondition: (status) => status?.toLowerCase() !== "not started",
	//},
];

const tableActions = [
	{
		label: "Add Client",
		action: () => {
			router.push("/client?new=true");
		},
		type: "button",
		style: "primary",
		icon: "pi pi-plus",
		layout: {
			position: "left",
			variant: "filled",
		},
		// Global action - always available
	},
	{
		label: "Create Estimate",
		rowAction: true,
		action: (rowData) => {
			const address = encodeURIComponent(rowData.address);
			router.push(`/estimate?new=true&address=${address}`);
		},
	},
	// {
	// 	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",
	// 	},
	// },
];
// 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];
				}
			});
		}

		// For cache key, use primary sort field/order for compatibility
		const primarySortField = filtersStore.getPrimarySortField("clients") || event.sortField;
		const primarySortOrder = filtersStore.getPrimarySortOrder("clients") || 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.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);
	} 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;
	}
};
// Status button click handlers
const handleAppointmentClick = (status, rowData) => {
	const address = encodeURIComponent(rowData.address);
	if (status?.toLowerCase() === "not started") {
		// Navigate to schedule on-site meeting
		router.push(`/calendar?tab=bids&new=true&address=${address}`);
	} else {
		// Navigate to view appointment details
		router.push('/calendar?tab=bids&address=' + address);
	}
};

const handleEstimateClick = (status, rowData) => {
	const address = encodeURIComponent(rowData.address);
	router.push(`/estimate?new=true&address=${address}`);
};

const handlePaymentClick = (status, rowData) => {
	notifications.addWarning("Payment view/create coming soon!");
	// const address = encodeURIComponent(rowData.address);
	// if (status?.toLowerCase() === "not started") {
	// 	// Navigate to payment processing
	// 	router.push(`/payments?new=true&address=${address}`);
	// }
	// else {
	// 	// Navigate to view payment details
	// 	router.push('/payments?address=' + address);
	// }
};

const handleJobClick = (status, rowData) => {
	notifications.addWarning("Job view/create coming soon!");
	// const address = encodeURIComponent(rowData.address);
	// if (status?.toLowerCase() === "not started") {
	// 	// Navigate to job creation
	// 	router.push(`/job?new=true&address=${address}`);
	// } else {
	// 	// Navigate to view job details
	// 	router.push('/job?address=' + address);
	// }
};

// Watch for filters change to update status counts
watch(
	() => filtersStore.getTableFilters("clients"),
	async () => {
		await refreshStatusCounts();
	},
	{ deep: true },
);

// Handle row click to navigate to client details
const handleRowClick = (event) => {
	const rowData = event.data;
	router.push(`/client?client=${rowData.customerName}&address=${rowData.address}`);
};

onMounted(async () => {
	// if lookup has a value (it will either be "customer" or "property", put focus onto the appropriate search input)
	if (lookup) {
		const inputElement = document.getElementById(`${lookup}SearchInput`);
		if (inputElement) {
			inputElement.focus();
		}
	}
	// 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 scoped>
<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;*/
}
.sidebar-button {
	justify-content: center;
}

.page-container {
	height: 100%;
	margin: 20px;
	gap: 20px;
	background-color: transparent;
}

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