<template>
	<div class="page-container">
		<h2>Invoices</h2>
		<!-- Todo Chart Section -->
		<div class = "widgets-grid">
			<!-- Ready to Invoice Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<CalendarCheck class="widget-icon" />
						<h3>Ready To Invoice</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Ready To Invoice"
								:categories="chartData.jobsToInvoice"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="filterBy('ready')">
							View Ready To Invoice
						</button>
					</div>
				</template>
			</Card>
			<!-- Late Balances Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<CardNoAccess class="widget-icon" />
						<h3>Late Balances</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Late Balances"
								:categories="chartData.invoicesLate"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="filterBy('late')">
							View Late Balances
						</button>
					</div>
				</template>
			</Card>
		</div>
		<DataTable
			:data="tableData"
			:columns="columns"
			tableName="invoices"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			@lazy-load="handleLazyLoad"
		/>
	</div>
</template>
<script setup>
import Card from "../common/Card.vue";
import DataTable from "../common/DataTable.vue";
import TodoChart from "../common/TodoChart.vue";
import { ref, onMounted, watch } from "vue";
import Api from "../../api";
import { useLoadingStore } from "../../stores/loading";
import { usePaginationStore } from "../../stores/pagination";
import { useFiltersStore } from "../../stores/filters";
import { useCompanyStore } from "../../stores/company.js";
import { CardNoAccess, CalendarCheck } from "@iconoir/vue";

const loadingStore = useLoadingStore();
const paginationStore = usePaginationStore();
const filtersStore = useFiltersStore();
const companyStore = useCompanyStore();

const tableData = ref([]);
const totalRecords = ref(0);
const isLoading = ref(false);

const chartData = ref({
	jobsToInvoice: {labels: ["Ready To Invoice"], data: [0], colors: ['green']},
	invoicesLate: {labels: ["Due", "30 Days", "60 Days", "80 Days"], data: [0, 0, 0, 0], colors: ["blue", "yellow", "orange", "red"]}
})

const columns = [
	{ label: "Customer Address", fieldName: "address", type: "text", sortable: true },
	{ label: "Customer", fieldName: "customer", type: "text", sortable: true, filterable: true },
	{
		label: "Status",
		fieldName: "status",
		type: "status-button",
		sortable: true,
		buttonVariant: "outlined",
		onStatusClick: (status, rowData) => handleInvoiceClick(status, rowData),
		//disableCondition: (status) => status?.toLowerCase() === "draft",
		disableCondition: false
	},
	{ label: "Grand Total", fieldName: "grandTotal", type: "text", sortable: true },
];

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

const handleInvoiceClick = () => {
}

const handleLazyLoad = async (event) => {
	console.log("Invoices page - handling lazy load:", event);

	try {
		isLoading.value = true;

		// Get sorting information from filters store first (needed for cache key)
		const sorting = filtersStore.getTableSorting("estimates");
		console.log("Current sorting state:", sorting);

		// 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];
				}
			});
		}

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

		// Call API with pagination, filters, and sorting
		const result = await Api.getPaginatedInvoiceDetails(paginationParams, filters, sorting);

		console.log("DEBUG: Result from api:", 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("invoices", result.pagination.total);

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

		console.log("Loaded from API:", {
			records: result.data.length,
			total: result.pagination.total,
			page: paginationParams.page + 1,
		});
	} catch (error) {
		console.error("Error loading invoice data:", error);
		// You could also show a toast or other error notification here
		tableData.value = [];
		totalRecords.value = 0;
	} finally {
		isLoading.value = false;
	}
};

// Load Chart Data
const loadChartData = async () => {
	chartData.value.jobsToInvoice.data = await Api.getJobsToInvoiceCount(companyStore.currentCompany);
	chartData.value.invoicesLate.data = await Api.getInvoicesLateCount(companyStore.currentCompany);
};

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

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

	await handleLazyLoad({
		page: initialPagination.page,
		rows: initialPagination.rows,
		first: initialPagination.first,
		sortField: initialSorting.field || initialPagination.sortField,
		sortOrder: initialSorting.order || initialPagination.sortOrder,
		filters: initialFilters,
	});

	await loadChartData();
});

watch(() => companyStore.currentCompany, async (newCompany, oldCompany) => {
	await loadChartData();
});

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