import React, { useEffect, useState } from "react";
import { useParams, Link } from "react-router-dom";
// import axios from "../../app/api";
import { ArrowLeft, MapPin, Package, CreditCard, Truck } from "lucide-react";
import {
  useGetOrderByIdQuery,
  useUpdateOrderStatusMutation,
} from "../../features/orders/ordersAPI";
import OrderHistoryDrawer from "../Orders/OrderHistoryDrawer";
import { Clock } from "lucide-react";
import StatusUpdateForm from "./StatusUpdateForm";

const StatusBadge = ({ status }) => {
  const styles = {
    PENDING: "bg-yellow-100 text-yellow-800",
    PROCESSING: "bg-purple-100 text-purple-800",
    SHIPPED: "bg-blue-100 text-blue-800",
    DELIVERED: "bg-green-100 text-green-800",
    CANCELLED: "bg-red-100 text-red-800",
  };
  return (
    <span
      className={`px-3 py-1 rounded-full text-xs font-semibold ${styles[status]}`}
    >
      {status}
    </span>
  );
};

const OrderDetails = () => {
  const { id } = useParams();
  // const [order, setOrder] = useState(null);
  // const [loading, setLoading] = useState(true);

  // useEffect(() => {
  //   axios
  //     .get(`/admin/orders/${id}`)
  //     .then((res) => {
  //       setOrder(res.data?.data || null);
  //       setLoading(false);
  //     })
  //     .catch(() => setLoading(false));
  // }, [id]);

  const { data, isLoading } = useGetOrderByIdQuery(id);
  const [updateOrderStatus, { isLoading: updating }] =
    useUpdateOrderStatusMutation();
  const [showHistory, setShowHistory] = useState(false);
  const [showStatusModal, setShowStatusModal] = useState(false);

  // const order = data?.data;
  // const order = data?.data?.order;
  // const order = data?.data?.order || data?.order || data;
  const order = data?.data;

  console.log("API DATA:", data);

  if (isLoading)
    return (
      <div className="flex justify-center items-center h-64 text-gray-600">
        Loading order details...
      </div>
    );

  if (!order)
    return (
      <div className="text-center py-10 text-gray-500">Order not found!</div>
    );

  return (
    <div className="max-w-7xl mx-auto p-6 space-y-6">
      {/* Back Button */}
      <div className="flex items-center gap-2 text-blue-600 hover:text-blue-800 transition">
        <ArrowLeft size={18} />
        <Link to="/orders" className="font-medium">
          Back to Orders
        </Link>
      </div>

      {/* Order Header */}
      <div className="bg-white shadow-lg rounded-2xl p-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">
            Order #{order.orderNumber}
          </h2>
          <p className="text-gray-500">
            {new Date(order.createdAt).toLocaleString()}
          </p>
          <div className="mt-2">
            <StatusBadge status={order.status} />
          </div>
        </div>
        <div className="text-right">
          <p className="text-2xl font-extrabold text-green-600">
            ₹{order.totalAmount}
          </p>
          <p className="text-gray-500 flex items-center gap-1">
            <CreditCard size={16} /> {order.paymentMethod} (
            {order.paymentStatus})
          </p>
        </div>

        {/* Admin Status Controls */}
        <button
          onClick={() => setShowStatusModal(true)}
          className="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-700 transition"
        >
          Update Status
        </button>
      </div>

      {/* Customer & Shipping */}
      <div className="grid md:grid-cols-2 gap-6">
        <div className="bg-gradient-to-r from-blue-50 to-blue-100 p-6 rounded-2xl shadow-md hover:shadow-lg transition">
          <h3 className="text-gray-700 font-semibold mb-3">Customer Info</h3>
          <p className="text-gray-800 font-medium">
            {order.user?.firstName} {order.user?.lastName}
          </p>
          <p className="text-gray-600">{order.user?.email}</p>
          <p className="text-gray-600">{order.user?.phone}</p>
        </div>

        <div className="bg-gradient-to-r from-green-50 to-green-100 p-6 rounded-2xl shadow-md hover:shadow-lg transition">
          <h3 className="text-gray-700 font-semibold mb-3 flex items-center gap-2">
            <MapPin size={16} /> Shipping Address
          </h3>
          <p className="text-gray-800">
            {/* {order.address.addressLine1}, {order.address.city} */}
            {order.address?.addressLine1}, {order.address?.city}
          </p>
          <p className="text-gray-600">
            {order.address?.state}, {order.address.country} -{" "}
            {order.address.postalCode}
          </p>
          <p className="text-gray-600">Phone: {order.address.phone}</p>
        </div>
      </div>

      {/* Items */}
      <div className="bg-white shadow-lg rounded-2xl p-6">
        <h3 className="text-gray-700 font-semibold mb-4 flex items-center gap-2">
          <Package size={16} /> Order Items
        </h3>
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm text-gray-700">
            <thead className="bg-gray-100 uppercase text-xs font-semibold">
              <tr>
                <th className="px-4 py-2">Product</th>
                <th className="px-4 py-2">Price</th>
                <th className="px-4 py-2">Qty</th>
                <th className="px-4 py-2 text-right">Subtotal</th>
              </tr>
            </thead>
            <tbody>
              {order.items?.map((item) => (
                <tr
                  key={item.id}
                  className="border-t hover:bg-gray-50 transition"
                >
                  <td className="px-4 py-2 font-medium">{item.productName}</td>
                  <td className="px-4 py-2">₹{item.price}</td>
                  <td className="px-4 py-2">{item.quantity}</td>
                  <td className="px-4 py-2 text-right font-semibold">
                    ₹{item.price * item.quantity}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Order Timeline */}

      <div className="bg-white shadow-xl rounded-3xl p-8">
        <div className="flex justify-between items-center mb-8">
          <h3 className="text-xl font-semibold text-gray-800">
            Order Timeline
          </h3>

          <button
            onClick={() => setShowHistory(true)}
            className="flex items-center gap-2 text-sm bg-gray-100 hover:bg-gray-200 px-4 py-2 rounded-lg transition"
          >
            <Clock size={16} />
            View History
          </button>
          <OrderHistoryDrawer
            orderId={order.id}
            open={showHistory}
            onClose={() => setShowHistory(false)}
          />
        </div>

        {(() => {
          const steps = [
            { key: "PENDING", label: "Order Placed" },
            { key: "PROCESSING", label: "Processing" },
            { key: "SHIPPED", label: "Shipped" },
            { key: "DELIVERED", label: "Delivered" },
          ];

          const currentStepIndex = steps.findIndex(
            (step) => step.key === order.status,
          );

          return (
            <div className="relative">
              {steps.map((step, index) => {
                const isCompleted = index < currentStepIndex;
                const isActive = index === currentStepIndex;
                const isLast = index === steps.length - 1;

                return (
                  <div
                    key={step.key}
                    className="relative flex items-start gap-6 pb-12"
                  >
                    {/* Vertical Line (ONLY if not last) */}
                    {!isLast && (
                      <div
                        className={`absolute left-4 top-10 w-1 h-full 
                  ${isCompleted ? "bg-green-500" : "bg-gray-200"}`}
                      ></div>
                    )}

                    {/* Circle */}
                    <div
                      className={`relative z-10 w-8 h-8 flex items-center justify-center rounded-full border-2 transition-all duration-300
                  ${
                    isCompleted
                      ? "bg-green-500 border-green-500 text-white"
                      : isActive
                        ? "bg-blue-600 border-blue-600 text-white"
                        : "bg-white border-gray-300 text-gray-400"
                  }
                `}
                    >
                      {isCompleted ? "✓" : index + 1}
                    </div>

                    {/* Content */}
                    <div>
                      <h4
                        className={`font-medium ${
                          isCompleted
                            ? "text-green-600"
                            : isActive
                              ? "text-blue-600"
                              : "text-gray-500"
                        }`}
                      >
                        {step.label}
                      </h4>

                      {isActive && (
                        <p className="text-sm text-gray-400 mt-1">
                          Currently in progress
                        </p>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          );
        })()}
      </div>

      {showStatusModal && (
  <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
    <div className="w-full max-w-lg">
      <StatusUpdateForm
        orderId={order.id}
        currentStatus={order.status}
      />

      <button
        onClick={() => setShowStatusModal(false)}
        className="mt-4 w-full bg-gray-200 py-2 rounded-lg"
      >
        Close
      </button>
    </div>
  </div>
)}

    </div>
  );
};

export default OrderDetails;
