<template>
	<div class="form-section">
		<div class="section-header">
			<i class="pi pi-map-marker" style="color: var(--primary-color); font-size: 1.2rem;"></i>
			<h3>Property Address Information</h3>
		</div>
		<div class="form-grid">
			<div
				v-for="(address, index) in localFormData.addresses"
				:key="index"
				class="address-item"
			>
				<div class="address-header">
					<div class="address-title">
						<i class="pi pi-home" style="font-size: 0.9rem; color: var(--primary-color);"></i>
						<h4>Address {{ index + 1 }}</h4>
					</div>
					<Button
						v-if="localFormData.addresses.length > 1"
						@click="removeAddress(index)"
						size="small"
						severity="danger"
						icon="pi pi-trash"
						class="remove-btn"
					/>
				</div>
				<div class="address-fields">
					<div class="form-field full-width">
						<label :for="`address-line1-${index}`">
							<i class="pi pi-map" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Address Line 1 <span class="required">*</span>
						</label>
						<InputText
							:id="`address-line1-${index}`"
							v-model="address.addressLine1"
							:disabled="isSubmitting"
							placeholder="Street address"
							class="w-full"
							@input="formatAddressLine(index, 'addressLine1', $event)"
						/>
					</div>
					<div class="form-field full-width">
						<label :for="`address-line2-${index}`"><i class="pi pi-map" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Address Line 2</label>
						<InputText
							:id="`address-line2-${index}`"
							v-model="address.addressLine2"
							:disabled="isSubmitting"
							placeholder="Apt, suite, unit, etc."
							class="w-full"
							@input="formatAddressLine(index, 'addressLine2', $event)"
						/>
					</div>
					<div class="form-field full-width checkbox-row">
						<input
							type="checkbox"
							:id="`isBilling-${index}`"
							v-model="address.isBillingAddress"
							:disabled="isSubmitting"
							@change="handleBillingChange(index)"
							style="margin-top: 0"
						/>
						<label :for="`isBilling-${index}`"><i class="pi pi-dollar" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Is Billing Address</label>
						<input
							type="checkbox"
							:id="`isService-${index}`"
							v-model="address.isServiceAddress"
							:disabled="isSubmitting"
							@change="handleServiceChange(index)"
							style="margin-top: 0; margin-left: 1.5rem;"
						/>
						<label :for="`isService-${index}`"><i class="pi pi-truck" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Is Service Address</label>
					</div>
					<div class="form-row">
						<div class="form-field">
							<label :for="`zipcode-${index}`">
								<i class="pi pi-hashtag" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Zip Code <span class="required">*</span>
							</label>
							<InputText
								:id="`zipcode-${index}`"
								v-model="address.pincode"
								:disabled="isSubmitting"
								@input="handleZipcodeInput(index, $event)"
								maxlength="5"
								placeholder="12345"
								class="w-full"
							/>
						</div>
						<div class="form-field">
							<label :for="`city-${index}`">
								<i class="pi pi-building" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>City <span class="required">*</span>
							</label>
							<InputText
								:id="`city-${index}`"
								v-model="address.city"
								:disabled="isSubmitting || address.zipcodeLookupDisabled"
								placeholder="City"
								class="w-full"
							/>
						</div>
						<div class="form-field">
							<label :for="`state-${index}`">
								<i class="pi pi-flag" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>State <span class="required">*</span>
							</label>
							<InputText
								:id="`state-${index}`"
								v-model="address.state"
								:disabled="isSubmitting || address.zipcodeLookupDisabled"
								placeholder="State"
								class="w-full"
							/>
						</div>
					</div>
					<div class="form-row">
						<div class="form-field">
							<label :for="`contacts-${index}`"><i class="pi pi-users" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Assigned Contacts</label>
							<MultiSelect
								:id="`contacts-${index}`"
								v-model="address.contacts"
								:options="contactOptions"
								optionLabel="label"
								optionValue="value"
								:disabled="isSubmitting || contactOptions.length === 0"
								placeholder="Select contacts"
								class="w-full"
								display="chip"
							/>
						</div>
						<div class="form-field">
							<label :for="`primaryContact-${index}`"><i class="pi pi-star-fill" style="font-size: 0.75rem; margin-right: 0.25rem;"></i>Primary Contact</label>
							<Select
								:id="`primaryContact-${index}`"
								v-model="address.primaryContact"
								:options="address.contacts.map(c => contactOptions.find(opt => opt.value === c))"
								optionLabel="label"
								optionValue="value"
								:disabled="isSubmitting || contactOptions.length === 0"
								placeholder="Select primary contact"
								class="w-full"
							/>
						</div>
					</div>
				</div>
			</div>
			<div class="form-field full-width">
				<Button label="Add another address" @click="addAddress" :disabled="isSubmitting" />
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import InputText from "primevue/inputtext";
import Select from "primevue/select";
import MultiSelect from "primevue/multiselect";
import Button from "primevue/button";
import Api from "../../api";
import { useNotificationStore } from "../../stores/notifications-primevue";

const props = defineProps({
	formData: {
		type: Object,
		required: true,
	},
	isSubmitting: {
		type: Boolean,
		default: false,
	},
	isEditMode: {
		type: Boolean,
		default: false,
	},
});

const emit = defineEmits(["update:formData"]);

const notificationStore = useNotificationStore();

const localFormData = computed({
	get: () => {
		if (!props.formData.addresses || props.formData.addresses.length === 0) {
			props.formData.addresses = [
				{
					addressLine1: "",
					addressLine2: "",
					isBillingAddress: true,
					isServiceAddress: true,
					pincode: "",
					city: "",
					state: "",
					contacts: [],
					primaryContact: null,
					zipcodeLookupDisabled: true,
				},
			];
		}
		return props.formData;
	},
	set: (value) => emit("update:formData", value),
});

const contactOptions = computed(() => {
	if (!localFormData.value.contacts || localFormData.value.contacts.length === 0) {
		return [];
	}
	return localFormData.value.contacts.map((contact, index) => ({
		label: `${contact.firstName || ""} ${contact.lastName || ""}`.trim() || `Contact ${index + 1}`,
		value: index,
	}));
});

onMounted(() => {
	if (!localFormData.value.addresses || localFormData.value.addresses.length === 0) {
		localFormData.value.addresses = [
			{
				addressLine1: "",
				addressLine2: "",
				isBillingAddress: true,
				isServiceAddress: true,
				pincode: "",
				city: "",
				state: "",
				contacts: [],
				primaryContact: null,
				zipcodeLookupDisabled: true,
			},
		];
	}
});

const addAddress = () => {
	localFormData.value.addresses.push({
		addressLine1: "",
		addressLine2: "",
		isBillingAddress: false,
		isServiceAddress: true,
		pincode: "",
		city: "",
		state: "",
		contacts: [],
		primaryContact: null,
		zipcodeLookupDisabled: true,
	});
};

const removeAddress = (index) => {
	if (localFormData.value.addresses.length > 1) {
		localFormData.value.addresses.splice(index, 1);
	}
};

const formatAddressLine = (index, field, event) => {
	const value = event.target.value;
	if (!value) return;
	
	// Capitalize first letter of each word
	const formatted = value
		.split(' ')
		.map(word => {
			if (!word) return word;
			return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
		})
		.join(' ');
	
	localFormData.value.addresses[index][field] = formatted;
};

const handleBillingChange = (selectedIndex) => {
	// If the selected address is now checked as billing
	if (localFormData.value.addresses[selectedIndex].isBillingAddress) {
		// Uncheck all other addresses
		localFormData.value.addresses.forEach((addr, idx) => {
			if (idx !== selectedIndex) {
				addr.isBillingAddress = false;
				addr.isServiceAddress = true; // Ensure service address is true for others
			}
		});

		// Auto-select all contacts
		if (contactOptions.value.length > 0) {
			localFormData.value.addresses[selectedIndex].contacts = contactOptions.value.map(
				(opt) => opt.value,
			);
		}

		// Auto-select primary contact
		if (localFormData.value.contacts && localFormData.value.contacts.length > 0) {
			const primaryIndex = localFormData.value.contacts.findIndex((c) => c.isPrimary);
			if (primaryIndex !== -1) {
				localFormData.value.addresses[selectedIndex].primaryContact = primaryIndex;
			} else {
				// Fallback to first contact if no primary found
				localFormData.value.addresses[selectedIndex].primaryContact = 0;
			}
		}
	} else {
		localFormData.value.addresses[selectedIndex].isBillingAddress = true;
		notificationStore.addInfo("At least one of Billing Address must be selected.");
	}
};

const handleServiceChange = (selectedIndex) => {
	// If the address does not have billing address selected, ensure that service address is always true
	if (!localFormData.value.addresses[selectedIndex].isBillingAddress) {
		localFormData.value.addresses[selectedIndex].isServiceAddress = true;
		notificationStore.addInfo("Service Address must be selected if not a Billing Address.");
	}
	if (!localFormData.value.addresses.some(addr => addr.isServiceAddress)) {
		localFormData.value.addresses[selectedIndex].isServiceAddress = true;
		notificationStore.addInfo("At least one Service Address must be selected.");
	}
};

const handleZipcodeInput = async (index, event) => {
	const input = event.target.value;

	// Only allow digits
	const digitsOnly = input.replace(/\D/g, "");

	// Limit to 5 digits
	if (digitsOnly.length > 5) {
		return;
	}

	localFormData.value.addresses[index].pincode = digitsOnly;

	// Reset city/state if zipcode is not complete
	if (digitsOnly.length < 5 && localFormData.value.addresses[index].zipcodeLookupDisabled) {
		localFormData.value.addresses[index].city = "";
		localFormData.value.addresses[index].state = "";
		localFormData.value.addresses[index].zipcodeLookupDisabled = false;
	}

	// Fetch city/state when 5 digits entered
	if (digitsOnly.length === 5) {
		try {
			console.log("DEBUG: Looking up city/state for zip code:", digitsOnly);
			const places = await Api.getCityStateByZip(digitsOnly);
			console.log("DEBUG: Retrieved places:", places);
			if (places && places.length > 0) {
				// Auto-populate city and state
				localFormData.value.addresses[index].city = places[0]["city"];
				localFormData.value.addresses[index].state = places[0]["state"];
				localFormData.value.addresses[index].zipcodeLookupDisabled = true;
				notificationStore.addSuccess(`Found: ${places[0]["city"]}, ${places[0]["state"]}`);
			}
		} catch (error) {
			// Enable manual entry if lookup fails
			localFormData.value.addresses[index].zipcodeLookupDisabled = false;
			notificationStore.addWarning(
				"Could not find city/state for this zip code. Please enter manually.",
			);
		}
	}
};
</script>

<style scoped>
.form-section {
	background: var(--surface-card);
	border-radius: 6px;
	padding: 0.75rem;
	border: 1px solid var(--surface-border);
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	transition: box-shadow 0.2s ease;
}

.form-section:hover {
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}

.section-header {
	display: flex;
	align-items: center;
	gap: 0.5rem;
	margin-bottom: 0.5rem;
	padding-bottom: 0.5rem;
	border-bottom: 2px solid var(--surface-border);
}

.section-header h3 {
	margin: 0;
	color: var(--text-color);
	font-size: 1.1rem;
	font-weight: 600;
}

.form-grid {
	display: flex;
	flex-direction: column;
	gap: 0.75rem;
}

.address-item {
	border: 1px solid var(--surface-border);
	border-radius: 6px;
	padding: 0.75rem;
	margin-bottom: 0.75rem;
	background: var(--surface-section);
	transition: all 0.2s ease;
}

.address-item:hover {
	border-color: var(--primary-color);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.address-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 0.75rem;
	padding-bottom: 0.5rem;
	border-bottom: 1px solid var(--surface-border);
}

.address-title {
	display: flex;
	align-items: center;
	gap: 0.5rem;
}

.address-header h4 {
	margin: 0;
	color: var(--text-color);
	font-size: 0.95rem;
	font-weight: 600;
}

.remove-btn {
	margin-left: auto;
}

.address-fields {
	display: flex;
	flex-direction: column;
	gap: 0.625rem;
}

.form-row {
	display: flex;
	gap: 0.625rem;
}

.form-field {
	display: flex;
	flex-direction: column;
	gap: 0.375rem;
	flex: 1;
}

.form-field.full-width {
	width: 100%;
}

.form-field label {
	font-weight: 500;
	color: var(--text-color);
	font-size: 0.85rem;
	display: flex;
	align-items: center;
}

.required {
	color: var(--red-500);
}

.w-full {
	width: 100% !important;
}

.form-field.checkbox-row {
	flex-direction: row;
	align-items: center;
	gap: 0.5rem;
}

.form-field.checkbox-row label {
	margin-bottom: 0;
	cursor: pointer;
}

@media (max-width: 768px) {
	.form-row {
		flex-direction: column;
	}

	.form-grid {
		grid-template-columns: 1fr;
	}
}
</style>
