<template>
	<div class="page-container">
		<h2>Estimates</h2>
		<!-- Todo Chart Section -->
		<div class="widgets-grid">
			<!-- Incomplete Bids Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<Edit class="widget-icon" />
						<h3>Incomplete Bids</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Incomplete Bids"
								:categories="chartData.bids"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="navigateTo('/calendar')">
							Incomplete Bids
						</button>
					</div>
				</template>
			</Card>
			<!-- Unapproved Estimates Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<ChatBubbleQuestion class="widget-icon" />
						<h3>Unapproved Estimates</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Unapproved Estimates"
								:categories="chartData.estimates"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="navigateTo('/estimates')">
							Unapproved Estimates
						</button>
					</div>
				</template>
			</Card>
			<!-- Half Down Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<CreditCard class="widget-icon" />
						<h3>Half Down Payments</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Half Down Payments"
								:categories="chartData.halfDown"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="navigateTo('/jobs')">
							Half Down Payments
						</button>
					</div>
				</template>
			</Card>
			<!-- Late Balances Widget -->
			<Card>
				<template #header>
					<div class="widget-header">
						<Hammer class="widget-icon" />
						<h3>Jobs In Queue</h3>
					</div>
				</template>
				<template #content>
					<div class="widget-content">
						<TodoChart
								title="Jobs In Queue"
								:categories="chartData.jobsInQueue"
								>
						</TodoChart>
						<button class="sidebar-button"
								@click="navigateTo('/jobs')">
							View Queued Jobs
						</button>
					</div>
				</template>
			</Card>
		</div>
		<DataTable
			:data="tableData"
			:columns="columns"
			:tableActions="tableActions"
			tableName="estimates"
			:lazy="true"
			:totalRecords="totalRecords"
			:loading="isLoading"
			@lazy-load="handleLazyLoad"
		/>
		<Modal
			:visible="showSubmitEstimateModal"
			@update:visible="showSubmitEstimateModal = $event"
			@close="closeSubmitEstimateModal"
			:options="{ showActions: false }"
		>
			<template #title>Add Item</template>
			<div class="modal-content">
				<DataTable
					:data="filteredItems"
					:columns="itemColumns"
					:tableName="'estimate-items'"
					:tableActions="tableActions"
					selectable
					:paginator="false"
					:rows="filteredItems.length"
				/>
			</div>
		</Modal>
	</div>
</template>
<script setup>
import Card from "../common/Card.vue";
import DataTable from "../common/DataTable.vue";
import TodoChart from "../common/TodoChart.vue";
import { Edit, ChatBubbleQuestion, CreditCard, Hammer } from "@iconoir/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 { useRouter } from "vue-router";
import { useCompanyStore } from "../../stores/company";

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

const tableData = ref([]);
const totalRecords = ref(0);
const isLoading = ref(false);
const showSubmitEstimateModal = ref(true);
const chartData = ref({
	bids: {labels: ["Unscheduled"], data: [0], colors: ['red']},
	estimates: {labels: ["Draft", "Submitted"], data: [0, 0], colors: ['orange', 'blue']},
	halfDown: {labels: ["Unpaid"], data: [0], colors: ['red']},
	jobsInQueue: {labels: ["Queued"], data: [0], colors: ['blue']}
});

//Junk
const filteredItems= []
// End junk

const columns = [
	{ label: "Estimate Address", fieldName: "address", type: "link", sortable: true, filterable:true,
		onLinkClick: (link, rowData) => handlePropertyClick(link, rowData),
	},
	//{ label: "Address", fieldName: "customInstallationAddress", type: "text", sortable: true },
	{ label: "Customer", fieldName: "customer", type: "link", sortable: true, filterable: true,
		onLinkClick: (link, rowData) => handleCustomerClick(link, rowData),
	},
	{
		label: "Status",
		fieldName: "status",
		type: "status-button",
		sortable: true,
		buttonVariant: "outlined",
		onStatusClick: (status, rowData) => {
			router.push(`/estimate?name=${encodeURIComponent(rowData.id)}`);
		},
		//disableCondition: (status) => status?.toLowerCase() === "draft",
		disableCondition: false
	},
	{ label: "Order Type", fieldName: "orderType", type: "text", sortable: true },
	//{ label: "Estimate Amount", fieldName:
];

const tableActions = [
	{
		label: "View Details",
		action: (rowData) => {
			router.push(`/estimate?name=${encodeURIComponent(rowData.id)}`);
		},
		type: "button",
		style: "info",
		icon: "pi pi-eye",
		requiresSelection: true,
		layout: {
			position: "center",
			variant: "outlined",
		},
	},
];

const closeSubmitEstimateModal = () => {
	showSubmitEstimateModal.value = false;
};

const handleCustomerClick = (link, rowData) => {
	console.log("DEBUG: Customer Link Clicked.");
	const client = encodeURIComponent(rowData.customer);
	const address = encodeURIComponent(rowData.address);
	router.push(`/client?client=${client}&address=${address}`);
}

const handlePropertyClick = (link, rowData) => {
	console.log("DEBUG: Property Link Clicked.");
	const client = encodeURIComponent(rowData.customer);
	const address = encodeURIComponent(rowData.address);
	router.push(`/property?client=${client}&address=${address}`);
}

const handleLazyLoad = async (event) => {
	console.log("Estimates 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 = {company: companyStore.currentCompany};
		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.getPaginatedEstimateDetails(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("estimates", result.pagination.total);

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

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



const loadChartData = async () => {
	chartData.value.bids.data = await Api.getIncompleteBidsCount(companyStore.currentCompany);
	chartData.value.estimates.data = await Api.getUnapprovedEstimatesCount(companyStore.currentCompany);
	chartData.value.halfDown.data = await Api.getEstimatesHalfDownCount(companyStore.currentCompany);
	chartData.value.jobsInQueue.data = await Api.getJobsInQueueCount(companyStore.currentCompany);
};

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

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

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

// watch the company store and refetch data when it changes
watch(
	() => companyStore.currentCompany,
	async (newCompany, oldCompany) => {
		console.log("Company changed from", oldCompany, "to", newCompany, "- refetching estimates data.");
		await handleLazyLoad({
			page: paginationStore.getTablePagination("estimates").page,
			rows: paginationStore.getTablePagination("estimates").rows,
			first: paginationStore.getTablePagination("estimates").first,
			filters: filtersStore.getTableFilters("estimates"),
		});
	}
);

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