"use client"

import { useState, useEffect } from "react"
import { getOrderEditHistory } from "@/lib/order"
import OrderChangeDetailsModal from "./OrderChangeDetailsModal"
import { toast } from "sonner"

const OrderEditHistory = ({ orderId }) => {
	const [history, setHistory] = useState([])
	const [loading, setLoading] = useState(true)
	const [error, setError] = useState(null)
	const [expanded, setExpanded] = useState(false)
	const [selectedEntry, setSelectedEntry] = useState(null)
	const [isModalOpen, setIsModalOpen] = useState(false)

	useEffect(() => {
		const fetchHistory = async () => {
			try {
				setLoading(true)
				const response = await getOrderEditHistory(orderId)
				if (response.status) {
					setHistory(response.data)
				} else {
					setError(response.message || "Failed to fetch order edit history")
					toast.error(response.message || "Failed to fetch order edit history", "error")
				}
			} catch (err) {
				setError("An error occurred while fetching the order edit history")
				toast.error("An error occurred while fetching the order edit history", "error")
			} finally {
				setLoading(false)
			}
		}

		if (orderId) {
			fetchHistory()
		}
	}, [orderId])

	// Function to format changes for display
	const formatChanges = (changes) => {
		return Object.keys(changes)
			.map((key) => {
				switch (key) {
					case "items":
						return "Products or quantities"
					case "address":
						return "Shipping address"
					case "city":
						return "City"
					case "postalCode":
						return "Postal code"
					case "country":
						return "Country"
					case "phone":
						return "Phone number"
					case "notes":
						return "Order notes"
					case "subtotal":
					case "totalAmount":
						return "" // Skip these as they're derived from items
					default:
						return key
				}
			})
			.filter((text) => text !== "")
			.join(", ")
	}

	// 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",
		}).format(date)
	}

	// Function to open the details modal
	const openDetailsModal = (entry) => {
		setSelectedEntry(entry)
		setIsModalOpen(true)
	}

	if (loading) {
		return (
			<div className="mt-6">
				<h3 className="text-lg font-medium mb-3">Order Edit History</h3>
				<div className="flex justify-center items-center py-4">
					<div className="animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-blue-500"></div>
				</div>
			</div>
		)
	}

	if (error) {
		return (
			<div className="mt-6">
				<h3 className="text-lg font-medium mb-3">Order Edit History</h3>
				<div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{error}</div>
			</div>
		)
	}

	if (history.length === 0) {
		return (
			<div className="mt-6">
				<h3 className="text-lg font-medium mb-3">Order Edit History</h3>
				<div className="text-gray-500 italic py-2 border rounded-lg p-4">No edit history available for this order.</div>
			</div>
		)
	}

	// Show only the last 3 entries when not expanded
	const displayedHistory = expanded ? history : history.slice(0, 3)
	const hasMoreEntries = history.length > 3

	return (
		<div className="mt-6">
			<div className="flex justify-between items-center mb-3">
				<h3 className="text-lg font-medium">Order Edit History</h3>
				{hasMoreEntries && (
					<button
						onClick={() => setExpanded(!expanded)}
						className="text-blue-600 hover:text-blue-800 text-sm font-medium"
					>
						{expanded ? "Show Less" : `Show All (${history.length})`}
					</button>
				)}
			</div>

			<div className="border rounded-lg overflow-hidden">
				<div className="bg-gray-50 p-4 border-b">
					<p className="text-sm text-gray-600">
						This section shows all changes made to this order. The most recent changes appear first.
					</p>
				</div>

				<div className="divide-y space-y-2 divide-gray-200">
					{displayedHistory.map((entry, index) => (
						<div key={index} className="p-4 hover:bg-gray-50 transition-colors">
							<div className="flex flex-col md:flex-row md:justify-between md:items-center mb-2">
								<span className="font-medium text-gray-900">{formatDate(entry.editedAt)}</span>
								<span className="text-sm text-gray-500">By: {entry.userId?.name || "Customer"}</span>
							</div>

							<div className="bg-blue-50 border-l-4 border-blue-500 p-3 mt-2">
								<p className="text-sm text-gray-700">
									<span className="font-medium">Changes:</span> {formatChanges(entry.changes)}
								</p>
							</div>

							{/* Add button to view detailed changes */}
							<button
								className="mt-2 text-sm text-blue-600 hover:text-blue-800 underline"
								onClick={() => openDetailsModal(entry)}
							>
								View detailed changes
							</button>
						</div>
					))}
				</div>
			</div>

			{hasMoreEntries && !expanded && (
				<div className="text-center mt-2">
					<button onClick={() => setExpanded(true)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">
						Show {history.length - 3} more entries
					</button>
				</div>
			)}

			{/* Render the details modal */}
			<OrderChangeDetailsModal
				isOpen={isModalOpen}
				onClose={() => setIsModalOpen(false)}
				historyEntry={selectedEntry}
			/>
		</div>
	)
}

export default OrderEditHistory
