<template>
	<Modal
		:visible="visible"
		@update:visible="$emit('update:visible', $event)"
		@close="handleClose"
		:options="{ showActions: false }"
	>
		<template #title>Save as Package</template>
		<div class="modal-content">
			<div class="form-section">
				<label for="packageName" class="field-label">
					Package Name
					<span class="required">*</span>
				</label>
				<InputText
					id="packageName"
					v-model="formData.packageName"
					placeholder="Enter package name"
					fluid
				/>
			</div>

			<div class="form-section">
				<label for="description" class="field-label">
					Description
				</label>
				<InputText
					id="description"
					v-model="formData.description"
					placeholder="Enter package description (optional)"
					fluid
				/>
			</div>

			<div class="form-section">
				<label for="codePrefix" class="field-label">
					Code Prefix
					<span class="required">*</span>
				</label>
				<Select
					id="codePrefix"
					v-model="formData.codePrefix"
					:options="codePrefixOptions"
					placeholder="Select a code prefix"
					fluid
				/>
			</div>

			<div class="form-section">
				<label for="category" class="field-label">
					Category
					<span class="required">*</span>
				</label>
				<Select
					id="category"
					v-model="formData.category"
					:options="categories"
					placeholder="Select a category"
					fluid
				/>
			</div>

			<div class="form-section">
				<label for="rate" class="field-label">
					Rate
					<span class="required">*</span>
				</label>
				<InputNumber
					id="rate"
					v-model="formData.rate"
					mode="currency"
					currency="USD"
					locale="en-US"
					:min="0"
					placeholder="$0.00"
					fluid
				/>
			</div>

			<div class="form-section">
				<h4>Package Contents</h4>
				<div v-if="items.length === 0" class="no-items">
					No items selected
				</div>
				<div v-else class="items-list">
					<div
						v-for="(item, index) in items"
						:key="index"
						class="package-item"
					>
						<div class="item-header" @click="toggleItemExpansion(index)">
							<div class="item-info">
								<i
									v-if="isPackage(item)"
									:class="[
										'pi',
										expandedItems.has(index) ? 'pi-chevron-down' : 'pi-chevron-right',
										'expand-icon'
									]"
								></i>
								<span class="item-name">{{ item.itemName || item.itemCode }}</span>
								<span v-if="isPackage(item)" class="package-badge">Package</span>
							</div>
							<span class="item-qty">Qty: {{ item.qty || 1 }}</span>
						</div>
						<div
							v-if="isPackage(item) && expandedItems.has(index)"
							class="package-contents"
						>
							<div
								v-for="(bomItem, bomIndex) in item.bom"
								:key="bomIndex"
								class="bom-item"
							>
								<span class="bom-item-name">{{ bomItem.itemName || bomItem.itemCode }}</span>
								<span class="bom-item-qty">Qty: {{ bomItem.qty || 1 }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="action-buttons">
				<Button label="Cancel" @click="handleClose" severity="secondary" />
				<Button
					label="Save Package"
					@click="handleSave"
					:disabled="!isFormValid"
				/>
			</div>
		</div>
	</Modal>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import Modal from "../common/Modal.vue";
import InputText from "primevue/inputtext";
import InputNumber from "primevue/inputnumber";
import Button from "primevue/button";
import Select from "primevue/select";
import Api from "../../api";
import { useNotificationStore } from "../../stores/notifications-primevue";

const props = defineProps({
	visible: {
		type: Boolean,
		required: true,
	},
	items: {
		type: Array,
		default: () => [],
	},
	defaultRate: {
		type: Number,
		default: 0,
	},
});

const emit = defineEmits(["update:visible", "save"]);

const notificationStore = useNotificationStore();

const formData = reactive({
	packageName: "",
	description: "",
	codePrefix: null,
	category: null,
	rate: null,
});

const codePrefixOptions = ref(["BLDR", "SNW-I"]);
const categories = ref([]);
const expandedItems = ref(new Set());
const isLoading = ref(false);

const isFormValid = computed(() => {
	return formData.packageName.trim() !== "" && 
	       formData.codePrefix !== null &&
	       formData.category !== null && 
	       formData.rate !== null && 
	       formData.rate > 0;
});

const isPackage = (item) => {
	return item.bom && Array.isArray(item.bom) && item.bom.length > 0;
};

const toggleItemExpansion = (index) => {
	const item = props.items[index];
	if (!isPackage(item)) return;

	if (expandedItems.value.has(index)) {
		expandedItems.value.delete(index);
	} else {
		expandedItems.value.add(index);
	}
};

const fetchCategories = async () => {
	try {
		isLoading.value = true;
		const result = await Api.getItemCategories();
		categories.value = result || [];
	} catch (error) {
		console.error("Error fetching item categories:", error);
		notificationStore.addNotification("Failed to fetch item categories", "error");
		categories.value = [];
	} finally {
		isLoading.value = false;
	}
};

const handleClose = () => {
	// Reset form
	formData.packageName = "";
	formData.description = "";
	formData.codePrefix = null;
	formData.category = null;
	formData.rate = null;
	expandedItems.value.clear();
	emit("update:visible", false);
};

const handleSave = () => {
	if (!isFormValid.value) {
		notificationStore.addNotification("Please fill in all required fields", "error");
		return;
	}

	const packageData = {
		packageName: formData.packageName,
		description: formData.description,
		codePrefix: formData.codePrefix,
		category: formData.category,
		rate: formData.rate,
		items: props.items.map(item => ({
			itemCode: item.itemCode,
			itemName: item.itemName,
			qty: item.qty || 1,
			uom: item.uom || item.stockUom,
		})),
	};

	emit("save", packageData);
	handleClose();
};

// Watch for modal opening to fetch categories
watch(
	() => props.visible,
	(newVal) => {
		if (newVal) {
			fetchCategories();
			// Set rate to defaultRate when modal opens
			if (props.defaultRate > 0) {
				formData.rate = props.defaultRate;
			}
		}
	}
);
</script>

<style scoped>
.modal-content {
	padding: 1.5rem;
	max-height: 70vh;
	overflow-y: auto;
}

.form-section {
	margin-bottom: 1.5rem;
}

.field-label {
	display: block;
	margin-bottom: 0.5rem;
	font-weight: 500;
	color: #333;
}

.required {
	color: red;
}

.no-items {
	padding: 2rem;
	text-align: center;
	color: #666;
	font-style: italic;
}

.items-list {
	border: 1px solid #e0e0e0;
	border-radius: 6px;
	overflow: hidden;
}

.package-item {
	border-bottom: 1px solid #e0e0e0;
}

.package-item:last-child {
	border-bottom: none;
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0.75rem 1rem;
	cursor: pointer;
	transition: background-color 0.2s;
}

.item-header:hover {
	background-color: #f8f9fa;
}

.item-info {
	display: flex;
	align-items: center;
	gap: 0.5rem;
	flex: 1;
}

.expand-icon {
	font-size: 0.8rem;
	color: #666;
}

.item-name {
	font-weight: 500;
	color: #333;
}

.package-badge {
	display: inline-block;
	padding: 0.2rem 0.5rem;
	background-color: #e3f2fd;
	color: #1976d2;
	border-radius: 4px;
	font-size: 0.75rem;
	font-weight: 500;
}

.item-qty {
	color: #666;
	font-size: 0.9rem;
}

.package-contents {
	background-color: #f8f9fa;
	padding: 0.5rem 1rem 0.5rem 2.5rem;
	border-top: 1px solid #e0e0e0;
}

.bom-item {
	display: flex;
	justify-content: space-between;
	padding: 0.5rem 0;
	color: #666;
	font-size: 0.9rem;
}

.bom-item-name {
	flex: 1;
}

.bom-item-qty {
	color: #999;
}

.action-buttons {
	display: flex;
	gap: 1rem;
	justify-content: flex-end;
	margin-top: 1.5rem;
	padding-top: 1rem;
	border-top: 1px solid #e0e0e0;
}
</style>
