import { defineStore } from "pinia";
import { FilterMatchMode } from "@primevue/core";

export const useFiltersStore = defineStore("filters", {
	state: () => ({
		// Store filters by table/component name
		tableFilters: {},
		// Store sorting by table/component name - now supports multiple sorts as array
		tableSorting: {},
	}),
	actions: {
		// Generic method to get filters for a specific table
		getTableFilters(tableName) {
			return this.tableFilters[tableName] || {};
		},

		// Generic method to get sorting for a specific table
		getTableSorting(tableName) {
			return this.tableSorting[tableName] || [];
		},

		// Get sorting in backend format: [["field", "asc/desc"], ["field", "asc/desc"]]
		getTableSortingForBackend(tableName) {
			const sorting = this.tableSorting[tableName] || [];
			console.log("getTableSortingForBackend - raw sorting:", sorting);

			const result = sorting.map((sort) => {
				const direction = sort.order === 1 ? "asc" : "desc";
				console.log("Converting sort:", {
					field: sort.field,
					order: sort.order,
					direction,
				});
				return [sort.field, direction];
			});

			console.log("getTableSortingForBackend result:", result);
			return result;
		},

		// Get primary sort field for compatibility with PrimeVue
		getPrimarySortField(tableName) {
			const sorting = this.tableSorting[tableName] || [];
			return sorting.length > 0 ? sorting[0].field : null;
		},

		// Get primary sort order for compatibility with PrimeVue
		getPrimarySortOrder(tableName) {
			const sorting = this.tableSorting[tableName] || [];
			if (sorting.length > 0) {
				const order = sorting[0].order;
				console.log("getPrimarySortOrder returning:", order, typeof order);
				return order;
			}
			return null;
		},

		// Generic method to update a specific filter
		updateTableFilter(tableName, fieldName, value, matchMode = null) {
			if (!this.tableFilters[tableName]) {
				this.tableFilters[tableName] = {};
			}
			if (!this.tableFilters[tableName][fieldName]) {
				this.tableFilters[tableName][fieldName] = {
					value: null,
					matchMode: FilterMatchMode.CONTAINS,
				};
			}
			this.tableFilters[tableName][fieldName].value = value;
			// Update match mode if provided
			if (matchMode) {
				this.tableFilters[tableName][fieldName].matchMode = matchMode;
			}
		},

		// Generic method to update sorting for a table (supports single sort from PrimeVue)
		updateTableSorting(tableName, field, order) {
			if (!this.tableSorting[tableName]) {
				this.tableSorting[tableName] = [];
			}

			// Clear sorting if no field provided or order is null/undefined
			if (!field || order === null || order === undefined) {
				console.log("Clearing sort for table:", tableName);
				this.tableSorting[tableName] = [];
				return;
			}

			// Ensure order is a number (PrimeVue uses 1 for asc, -1 for desc)
			let numericOrder = order;
			if (typeof order === "string") {
				numericOrder = order.toLowerCase() === "asc" ? 1 : -1;
			} else if (typeof order === "number") {
				// Ensure it's 1 or -1
				numericOrder = order > 0 ? 1 : -1;
			} else {
				console.warn("Invalid sort order type:", typeof order, order);
				return;
			}

			console.log("updateTableSorting called with:", {
				tableName,
				field,
				order,
				numericOrder,
			});

			// Replace existing sort with new single sort (PrimeVue behavior)
			this.tableSorting[tableName] = [{ field, order: numericOrder }];
		},

		// Method to add or update a specific sort field (for multi-sort support)
		addTableSort(tableName, field, order) {
			if (!this.tableSorting[tableName]) {
				this.tableSorting[tableName] = [];
			}

			// Remove existing sort for this field
			this.tableSorting[tableName] = this.tableSorting[tableName].filter(
				(sort) => sort.field !== field,
			);

			// Add new sort if field and order provided
			if (field && order) {
				this.tableSorting[tableName].push({ field, order });
			}
		},

		// Method to set multiple sorts at once
		setTableSorting(tableName, sortArray) {
			this.tableSorting[tableName] = sortArray || [];
		},

		// Method to clear all filters for a table
		clearTableFilters(tableName) {
			if (this.tableFilters[tableName]) {
				Object.keys(this.tableFilters[tableName]).forEach((key) => {
					this.tableFilters[tableName][key].value = null;
				});
			}
		},

		// Method to clear sorting for a table
		clearTableSorting(tableName) {
			this.tableSorting[tableName] = [];
		},

		// Method to clear both filters and sorting for a table
		clearTableState(tableName) {
			this.clearTableFilters(tableName);
			this.clearTableSorting(tableName);
		},

		// Method to initialize filters for a table if they don't exist
		initializeTableFilters(tableName, columns) {
			if (!this.tableFilters[tableName]) {
				this.tableFilters[tableName] = {};
			}

			columns.forEach((column) => {
				if (column.filterable && !this.tableFilters[tableName][column.fieldName]) {
					this.tableFilters[tableName][column.fieldName] = {
						value: null,
						matchMode: FilterMatchMode.CONTAINS,
					};
				}
			});
		},

		// Method to initialize sorting for a table
		initializeTableSorting(tableName) {
			if (!this.tableSorting[tableName]) {
				this.tableSorting[tableName] = [];
			}
		},

		// Method to get active filters count
		getActiveFiltersCount(tableName) {
			const filters = this.getTableFilters(tableName);
			return Object.values(filters).filter(
				(filter) => filter.value && filter.value.trim() !== "",
			).length;
		},

		// Method to check if sorting is active
		isSortingActive(tableName) {
			const sorting = this.getTableSorting(tableName);
			return sorting.length > 0;
		},

		// Method to get all table state (filters + sorting)
		getTableState(tableName) {
			return {
				filters: this.getTableFilters(tableName),
				sorting: this.getTableSorting(tableName),
			};
		},

		// Legacy method for backward compatibility
		setClientNameFilter(filterValue) {
			this.updateTableFilter("clients", "addressTitle", filterValue);
		},

		// Getter for legacy compatibility
		get clientNameFilter() {
			return this.tableFilters?.clients?.addressTitle?.value || "";
		},
	},
});
