import React from "react";
import { useNavigate } from "react-router-dom";

const statusStyles = {
  DELIVERED: "bg-green-100 text-green-700 ring-1 ring-green-200",
  PENDING: "bg-yellow-100 text-yellow-700 ring-1 ring-yellow-200",
  SHIPPED: "bg-blue-100 text-blue-700 ring-1 ring-blue-200",
  CANCELLED: "bg-red-100 text-red-700 ring-1 ring-red-200",
};

const statusDotStyles = {
  DELIVERED: "bg-green-500",
  PENDING: "bg-yellow-500",
  SHIPPED: "bg-blue-500",
  CANCELLED: "bg-red-500",
};

const RecentOrders = ({ recentOrders, topProducts }) => {
  const navigate = useNavigate();

  const getProductImage = (order) => {
    const productImage = order.items?.[0]?.productImage;
    if (productImage && productImage !== "https://via.placeholder.com/300")
      return productImage;
    const productId = order.items?.[0]?.productId;
    if (productId) {
      const product = topProducts?.find((p) => p._id === productId);
      if (product?.displayImage) return product.displayImage;
    }
    return "/bitmap.png";
  };

  const getProductName = (order) => {
    const productDetails = order.items?.[0]?.productDetails;
    if (productDetails?.name) return productDetails.name;
    const product = topProducts?.find(
      (p) => p._id === order.items[0]?.productId,
    );
    return product?.name || order.items[0]?.productName || "Product";
  };

  return (
    <div className="bg-white shadow-xl rounded-2xl border border-gray-100 overflow-hidden hover:shadow-2xl transition-shadow duration-300">
      <div className="bg-gradient-to-r from-[#704F38] to-[#8d6449] p-6">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-2xl font-bold text-white">Recent Orders</h3>
            <p className="text-gray-200 text-sm mt-1">
              Latest {recentOrders?.length || 0} transactions
            </p>
          </div>
          <button
            onClick={() => navigate("/orders")}
            className="bg-white text-[#704F38] px-4 py-2 rounded-lg font-semibold hover:bg-gray-100 transition-colors"
          >
            View All
          </button>
        </div>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              {[
                "Order Details",
                "Customer",
                "Amount",
                "Status",
                "Payment",
                "Date",
              ].map((h) => (
                <th
                  key={h}
                  className="px-6 py-4 text-left text-xs font-bold text-gray-600 uppercase tracking-wider"
                >
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {recentOrders?.map((order) => (
              <tr
                key={order.id}
                className="hover:bg-gray-50 transition-colors duration-200 cursor-pointer"
                onClick={() => navigate(`/orders/${order.id}`)}
              >
                <td className="px-6 py-4">
                  <div className="flex items-center gap-4">
                    <div className="relative">
                      <img
                        src={getProductImage(order)}
                        alt={getProductName(order)}
                        className="w-16 h-16 object-cover rounded-xl shadow-md ring-2 ring-gray-100"
                        onError={(e) => {
                          e.target.src = "/bitmap.png";
                        }}
                      />
                      {order.items.length > 1 && (
                        <div className="absolute -top-2 -right-2 bg-[#704F38] text-white text-xs font-bold rounded-full w-6 h-6 flex items-center justify-center">
                          {order.items.length}
                        </div>
                      )}
                    </div>
                    <div>
                      <p className="font-bold text-gray-900 text-sm">
                        {order.orderNumber}
                      </p>
                      <p className="text-xs text-gray-500 mt-1">
                        {getProductName(order)}
                      </p>
                    </div>
                  </div>
                </td>

                <td className="px-6 py-4">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-gradient-to-br from-[#704F38] to-[#8d6449] rounded-full flex items-center justify-center text-white font-bold text-sm">
                      {order.user.firstName?.[0]}
                      {order.user.lastName?.[0]}
                    </div>
                    <div>
                      <p className="font-semibold text-gray-900 text-sm">
                        {order.user.firstName} {order.user.lastName}
                      </p>
                      <p className="text-xs text-gray-500">
                        {order.user.email}
                      </p>
                    </div>
                  </div>
                </td>

                <td className="px-6 py-4">
                  <p className="font-bold text-lg text-[#704F38]">
                    ₹{parseFloat(order.totalAmount).toLocaleString()}
                  </p>
                  <p className="text-xs text-gray-500 mt-1 uppercase">
                    {order.paymentMethod}
                  </p>
                </td>

                <td className="px-6 py-4">
                  <span
                    className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-bold shadow-sm ${statusStyles[order.status] || "bg-purple-100 text-purple-700 ring-1 ring-purple-200"}`}
                  >
                    <span
                      className={`w-2 h-2 rounded-full ${statusDotStyles[order.status] || "bg-purple-500"}`}
                    ></span>
                    {order.status}
                  </span>
                </td>

                <td className="px-6 py-4">
                  <span
                    className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-bold shadow-sm ${order.paymentStatus === "PAID" ? "bg-emerald-100 text-emerald-700 ring-1 ring-emerald-200" : "bg-orange-100 text-orange-700 ring-1 ring-orange-200"}`}
                  >
                    {order.paymentStatus === "PAID" ? "✓" : "⏱"}{" "}
                    {order.paymentStatus}
                  </span>
                </td>

                <td className="px-6 py-4">
                  <p className="text-sm text-gray-900">
                    {new Date(order.createdAt).toLocaleDateString("en-US", {
                      month: "short",
                      day: "numeric",
                    })}
                  </p>
                  <p className="text-xs text-gray-500">
                    {new Date(order.createdAt).toLocaleTimeString("en-US", {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </p>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {(!recentOrders || recentOrders.length === 0) && (
        <div className="text-center py-12">
          <svg
            className="w-16 h-16 text-gray-300 mx-auto mb-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
            />
          </svg>
          <p className="text-gray-500 text-lg">No recent orders found</p>
        </div>
      )}
    </div>
  );
};

export default RecentOrders;
