"use client"

import { useState, useEffect } from "react"
import { updateOrderByCustomer } from "@/lib/order"
const EditOrderModal = ({ order, isOpen, onClose, onOrderUpdated }) => {
	const [editedOrder, setEditedOrder] = useState(null)
	const [loading, setLoading] = useState(false)
	const [error, setError] = useState(null)
	const { showToast } = Toast()
	const [showConfirmation, setShowConfirmation] = useState(false)

	// Determine what can be edited based on order status
	const canEditQuantity = order?.paymentStatus !== "paid" && order?.orderStatus === "processing"
	const canEditShipping = !["shipped", "delivered"].includes(order?.orderStatus)

	useEffect(() => {
		if (order) {
			setEditedOrder({
				...order,
				items: [...order.items],
			})
		}
	}, [order])

	if (!isOpen || !editedOrder) return null

	const handleQuantityChange = (index, newQuantity) => {
		if (!canEditQuantity) {
			toast.success("Cannot change quantity for paid orders", "error")
			return
		}

		if (newQuantity < 1) newQuantity = 1

		const updatedItems = [...editedOrder.items]
		updatedItems[index] = {
			...updatedItems[index],
			quantity: newQuantity,
		}

		// Recalculate subtotal
		const subtotal = updatedItems.reduce((sum, item) => sum + item.price * item.quantity, 0)

		setEditedOrder({
			...editedOrder,
			items: updatedItems,
			subtotal,
			totalAmount: subtotal + (editedOrder.shipping || 0),
		})
	}

	const handleAddressChange = (e) => {
		if (!canEditShipping) {
			toast.success("Cannot change shipping address for shipped orders", "error")
			return
		}

		setEditedOrder({
			...editedOrder,
			[e.target.name]: e.target.value,
		})
	}

	// Modify the handleSubmit function
	const handleSubmit = async (e) => {
		e.preventDefault()
		// Show confirmation dialog instead of immediately submitting
		setShowConfirmation(true)
	}

	// Add a new function to handle the actual submission
	const confirmSubmit = async () => {
		setShowConfirmation(false)
		setLoading(true)
		setError(null)

		try {
			console.log("Preparing to update order:", editedOrder._id)

			// Only send the fields that can be edited
			const dataToUpdate = {
				items: canEditQuantity ? editedOrder.items : undefined,
				address: canEditShipping ? editedOrder.address : undefined,
				city: canEditShipping ? editedOrder.city : undefined,
				postalCode: canEditShipping ? editedOrder.postalCode : undefined,
				country: canEditShipping ? editedOrder.country : undefined,
				phone: editedOrder.phone, // Phone can always be edited
				notes: editedOrder.notes, // Notes can always be edited
			}

			// Filter out undefined values
			Object.keys(dataToUpdate).forEach((key) => {
				if (dataToUpdate[key] === undefined) {
					delete dataToUpdate[key]
				}
			})

			console.log("Sending update with data:", dataToUpdate)

			// Make sure we're using the correct function from our lib
			const result = await updateOrderByCustomer(editedOrder._id, dataToUpdate)
			console.log("Update result:", result)

			if (result.status) {
				toast.success("Order updated successfully", "success")
				onOrderUpdated(result.data)
				onClose()
			} else {
				setError(result.message || "Failed to update order")
				toast.success(result.message || "Failed to update order", "error")
			}
		} catch (err) {
			console.error("Error in confirmSubmit:", err)
			setError("An error occurred while updating the order")
			toast.success("An error occurred while updating the order", "error")
		} finally {
			setLoading(false)
		}
	}

	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-2xl 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">Edit Order #{editedOrder._id}</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>

					{error && <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{error}</div>}

					<form onSubmit={handleSubmit}>
						{/* Order Items Section */}
						<div className="mb-6">
							<h3 className="text-lg font-medium mb-2">Order Items</h3>
							{!canEditQuantity && (
								<p className="text-amber-600 text-sm mb-2">Quantities cannot be changed for paid orders</p>
							)}
							<div className="border rounded-lg overflow-hidden">
								<table className="min-w-full divide-y divide-gray-200">
									<thead className="bg-gray-50">
										<tr>
											<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
												Product
											</th>
											<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
												Price
											</th>
											<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
												Quantity
											</th>
											<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
												Total
											</th>
										</tr>
									</thead>
									<tbody className="bg-white divide-y divide-gray-200">
										{editedOrder.items.map((item, index) => (
											<tr key={index}>
												<td className="px-6 py-4 whitespace-nowrap">{item.name}</td>
												<td className="px-6 py-4 whitespace-nowrap">€{item.price.toFixed(2)}</td>
												<td className="px-6 py-4 whitespace-nowrap">
													{canEditQuantity ? (
														<div className="flex items-center">
															<button
																type="button"
																className="bg-gray-200 px-2 py-1 rounded-l"
																onClick={() => handleQuantityChange(index, item.quantity - 1)}
																disabled={item.quantity <= 1}
															>
																-
															</button>
															<span className="px-4">{item.quantity}</span>
															<button
																type="button"
																className="bg-gray-200 px-2 py-1 rounded-r"
																onClick={() => handleQuantityChange(index, item.quantity + 1)}
															>
																+
															</button>
														</div>
													) : (
														item.quantity
													)}
												</td>
												<td className="px-6 py-4 whitespace-nowrap">€{(item.price * item.quantity).toFixed(2)}</td>
											</tr>
										))}
									</tbody>
									<tfoot className="bg-gray-50">
										<tr>
											<td colSpan="3" className="px-6 py-3 text-right font-medium">
												Subtotal:
											</td>
											<td className="px-6 py-3">€{editedOrder.subtotal.toFixed(2)}</td>
										</tr>
										<tr>
											<td colSpan="3" className="px-6 py-3 text-right font-medium">
												Shipping:
											</td>
											<td className="px-6 py-3">€{editedOrder.shipping.toFixed(2)}</td>
										</tr>
										<tr>
											<td colSpan="3" className="px-6 py-3 text-right font-medium">
												Total:
											</td>
											<td className="px-6 py-3 font-bold">€{editedOrder.totalAmount.toFixed(2)}</td>
										</tr>
									</tfoot>
								</table>
							</div>
						</div>

						{/* Shipping Address Section */}
						<div className="mb-6">
							<h3 className="text-lg font-medium mb-2">Shipping Address</h3>
							{!canEditShipping && (
								<p className="text-amber-600 text-sm mb-2">Shipping address cannot be changed for shipped orders</p>
							)}
							<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div>
									<label className="block text-sm font-medium text-gray-700 mb-1">Address</label>
									<input
										type="text"
										name="address"
										value={editedOrder.address}
										onChange={handleAddressChange}
										disabled={!canEditShipping}
										className={`w-full p-2 border rounded-md ${!canEditShipping ? "bg-gray-100" : ""}`}
									/>
								</div>
								<div>
									<label className="block text-sm font-medium text-gray-700 mb-1">City</label>
									<input
										type="text"
										name="city"
										value={editedOrder.city}
										onChange={handleAddressChange}
										disabled={!canEditShipping}
										className={`w-full p-2 border rounded-md ${!canEditShipping ? "bg-gray-100" : ""}`}
									/>
								</div>
								<div>
									<label className="block text-sm font-medium text-gray-700 mb-1">Postal Code</label>
									<input
										type="text"
										name="postalCode"
										value={editedOrder.postalCode}
										onChange={handleAddressChange}
										disabled={!canEditShipping}
										className={`w-full p-2 border rounded-md ${!canEditShipping ? "bg-gray-100" : ""}`}
									/>
								</div>
								<div>
									<label className="block text-sm font-medium text-gray-700 mb-1">Country</label>
									<input
										type="text"
										name="country"
										value={editedOrder.country}
										onChange={handleAddressChange}
										disabled={!canEditShipping}
										className={`w-full p-2 border rounded-md ${!canEditShipping ? "bg-gray-100" : ""}`}
									/>
								</div>
							</div>
						</div>

						{/* Phone Number Section */}
						<div className="mb-6">
							<h3 className="text-lg font-medium mb-2">Contact Information</h3>
							<div>
								<label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
								<input
									type="text"
									name="phone"
									value={editedOrder.phone || ""}
									onChange={(e) => setEditedOrder({ ...editedOrder, phone: e.target.value })}
									className="w-full p-2 border rounded-md"
								/>
							</div>
						</div>

						{/* Order Notes Section */}
						<div className="mb-6">
							<h3 className="text-lg font-medium mb-2">Order Notes</h3>
							<textarea
								name="notes"
								value={editedOrder.notes || ""}
								onChange={(e) => setEditedOrder({ ...editedOrder, notes: e.target.value })}
								className="w-full p-2 border rounded-md h-24"
								placeholder="Add any special instructions or notes for this order"
							/>
						</div>

						<div className="flex justify-end space-x-3">
							<button
								type="button"
								onClick={onClose}
								className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
								disabled={loading}
							>
								Cancel
							</button>
							<button
								type="submit"
								className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
								disabled={loading}
							>
								{loading ? "Saving..." : "Save Changes"}
							</button>
						</div>
					</form>
				</div>
			</div>

			{showConfirmation && (
				<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
					<div className="bg-white rounded-lg p-6 max-w-md w-full">
						<h3 className="text-lg font-medium mb-4">Confirm Changes</h3>
						<p className="mb-4">Are you sure you want to save these changes to your order?</p>
						<div className="flex justify-end space-x-3">
							<button
								type="button"
								onClick={() => setShowConfirmation(false)}
								className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
							>
								Cancel
							</button>
							<button
								type="button"
								onClick={confirmSubmit}
								className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
								disabled={loading}
							>
								{loading ? "Saving..." : "Confirm"}
							</button>
						</div>
					</div>
				</div>
			)}
		</div>
	)
}

export default EditOrderModal
