"use client"

const OrderChangeDetailsModal = ({ isOpen, onClose, historyEntry }) => {
	if (!isOpen || !historyEntry) return null

	// Function to format date
	const formatDate = (dateString) => {
		const date = new Date(dateString)
		return new Intl.DateTimeFormat("en-US", {
			year: "numeric",
			month: "short",
			day: "numeric",
			hour: "2-digit",
			minute: "2-digit",
			second: "2-digit",
		}).format(date)
	}

	// Function to format currency
	const formatCurrency = (amount) => {
		return `€${Number.parseFloat(amount).toFixed(2)}`
	}

	// Function to check if a value has changed
	const hasChanged = (key) => {
		if (!historyEntry.previousState || !historyEntry.newState) return false

		// Special handling for items array
		if (key === "items") {
			return JSON.stringify(historyEntry.previousState[key]) !== JSON.stringify(historyEntry.newState[key])
		}

		return historyEntry.previousState[key] !== historyEntry.newState[key]
	}

	// Function to get change class (for highlighting changes)
	const getChangeClass = (key) => {
		return hasChanged(key) ? "bg-yellow-50" : ""
	}

	// Function to render item changes
	const renderItemChanges = () => {
		if (!historyEntry.previousState?.items || !historyEntry.newState?.items) return null

		const prevItems = historyEntry.previousState.items
		const newItems = historyEntry.newState.items

		// Create a map of all items by ID
		const allItemIds = new Set()
		prevItems.forEach((item) => allItemIds.add(item.id || item._id))
		newItems.forEach((item) => allItemIds.add(item.id || item._id))

		return (
			<div className="mt-4">
				<h4 className="font-medium text-gray-900 mb-2">Product Changes</h4>
				<div className="overflow-x-auto">
					<table className="min-w-full divide-y divide-gray-200">
						<thead className="bg-gray-50">
							<tr>
								<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									Product
								</th>
								<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									Previous Quantity
								</th>
								<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									New Quantity
								</th>
								<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									Price
								</th>
								<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									Change
								</th>
							</tr>
						</thead>
						<tbody className="bg-white divide-y divide-gray-200">
							{Array.from(allItemIds).map((itemId) => {
								const prevItem = prevItems.find((item) => (item.id || item._id) === itemId) || {
									name: "N/A",
									quantity: 0,
									price: 0,
								}
								const newItem = newItems.find((item) => (item.id || item._id) === itemId) || {
									name: "N/A",
									quantity: 0,
									price: 0,
								}
								const quantityChanged = prevItem.quantity !== newItem.quantity
								const isNewItem = prevItem.quantity === 0
								const isRemovedItem = newItem.quantity === 0

								return (
									<tr key={itemId} className={quantityChanged ? "bg-yellow-50" : ""}>
										<td className="px-4 py-2 whitespace-nowrap">{newItem.name || prevItem.name}</td>
										<td className="px-4 py-2 whitespace-nowrap">{prevItem.quantity}</td>
										<td className="px-4 py-2 whitespace-nowrap">{newItem.quantity}</td>
										<td className="px-4 py-2 whitespace-nowrap">{formatCurrency(newItem.price || prevItem.price)}</td>
										<td className="px-4 py-2 whitespace-nowrap">
											{isNewItem && <span className="text-green-600">Added</span>}
											{isRemovedItem && <span className="text-red-600">Removed</span>}
											{quantityChanged && !isNewItem && !isRemovedItem && (
												<span className={newItem.quantity > prevItem.quantity ? "text-green-600" : "text-red-600"}>
													{newItem.quantity > prevItem.quantity ? "+" : ""}
													{newItem.quantity - prevItem.quantity}
												</span>
											)}
										</td>
									</tr>
								)
							})}
						</tbody>
					</table>
				</div>
			</div>
		)
	}

	return (
		<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
			<div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
				<div className="p-6">
					<div className="flex justify-between items-center mb-4">
						<h2 className="text-xl font-semibold">Detailed Order Changes</h2>
						<button onClick={onClose} className="text-gray-500 hover:text-gray-700">
							<svg
								xmlns="http://www.w3.org/2000/svg"
								className="h-6 w-6"
								fill="none"
								viewBox="0 0 24 24"
								stroke="currentColor"
							>
								<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
							</svg>
						</button>
					</div>

					<div className="mb-4">
						<p className="text-sm text-gray-600">
							<span className="font-medium">Edit Date:</span> {formatDate(historyEntry.editedAt)}
						</p>
						<p className="text-sm text-gray-600">
							<span className="font-medium">Edited By:</span> {historyEntry.userId?.name || "Customer"}
						</p>
					</div>

					{/* Render item changes if items were modified */}
					{hasChanged("items") && renderItemChanges()}

					{/* Shipping Address Changes */}
					{(hasChanged("address") || hasChanged("city") || hasChanged("postalCode") || hasChanged("country")) && (
						<div className="mt-4">
							<h4 className="font-medium text-gray-900 mb-2">Shipping Address Changes</h4>
							<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div>
									<h5 className="text-sm font-medium text-gray-700">Previous Address</h5>
									<div className="border rounded-md p-3 bg-gray-50">
										<p>{historyEntry.previousState.address}</p>
										<p>
											{historyEntry.previousState.city}, {historyEntry.previousState.postalCode}
										</p>
										<p>{historyEntry.previousState.country}</p>
									</div>
								</div>
								<div>
									<h5 className="text-sm font-medium text-gray-700">New Address</h5>
									<div className="border rounded-md p-3 bg-white">
										<p>{historyEntry.newState.address}</p>
										<p>
											{historyEntry.newState.city}, {historyEntry.newState.postalCode}
										</p>
										<p>{historyEntry.newState.country}</p>
									</div>
								</div>
							</div>
						</div>
					)}

					{/* Contact Information Changes */}
					{hasChanged("phone") && (
						<div className="mt-4">
							<h4 className="font-medium text-gray-900 mb-2">Contact Information Changes</h4>
							<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div>
									<h5 className="text-sm font-medium text-gray-700">Previous Phone</h5>
									<div className="border rounded-md p-3 bg-gray-50">
										<p>{historyEntry.previousState.phone || "Not provided"}</p>
									</div>
								</div>
								<div>
									<h5 className="text-sm font-medium text-gray-700">New Phone</h5>
									<div className="border rounded-md p-3 bg-white">
										<p>{historyEntry.newState.phone || "Not provided"}</p>
									</div>
								</div>
							</div>
						</div>
					)}

					{/* Order Notes Changes */}
					{hasChanged("notes") && (
						<div className="mt-4">
							<h4 className="font-medium text-gray-900 mb-2">Order Notes Changes</h4>
							<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div>
									<h5 className="text-sm font-medium text-gray-700">Previous Notes</h5>
									<div className="border rounded-md p-3 bg-gray-50">
										<p>{historyEntry.previousState.notes || "No notes"}</p>
									</div>
								</div>
								<div>
									<h5 className="text-sm font-medium text-gray-700">New Notes</h5>
									<div className="border rounded-md p-3 bg-white">
										<p>{historyEntry.newState.notes || "No notes"}</p>
									</div>
								</div>
							</div>
						</div>
					)}

					{/* Order Totals Changes */}
					{(hasChanged("subtotal") || hasChanged("totalAmount")) && (
						<div className="mt-4">
							<h4 className="font-medium text-gray-900 mb-2">Order Totals Changes</h4>
							<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div>
									<h5 className="text-sm font-medium text-gray-700">Previous Totals</h5>
									<div className="border rounded-md p-3 bg-gray-50">
										<p>
											<span className="font-medium">Subtotal:</span>{" "}
											{formatCurrency(historyEntry.previousState.subtotal)}
										</p>
										<p>
											<span className="font-medium">Total:</span>{" "}
											{formatCurrency(historyEntry.previousState.totalAmount)}
										</p>
									</div>
								</div>
								<div>
									<h5 className="text-sm font-medium text-gray-700">New Totals</h5>
									<div className="border rounded-md p-3 bg-white">
										<p>
											<span className="font-medium">Subtotal:</span> {formatCurrency(historyEntry.newState.subtotal)}
										</p>
										<p>
											<span className="font-medium">Total:</span> {formatCurrency(historyEntry.newState.totalAmount)}
										</p>
									</div>
								</div>
							</div>
						</div>
					)}

					<div className="mt-6 flex justify-end">
						<button onClick={onClose} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
							Close
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

export default OrderChangeDetailsModal
