import React from "react";
import { useParams, Link } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
import { useGetReturnRequestByIdQuery } from "../../../features/orders/ordersAPI";

const ReturnDetails = () => {
  const { id } = useParams();
  const { data, isLoading, isError } = useGetReturnRequestByIdQuery(id);

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

  if (isError || !data?.data)
    return (
      <div className="text-center mt-10 text-red-600">
        Return request not found!
      </div>
    );

  const order = data.data;

  return (
    <div className="max-w-5xl mx-auto space-y-8">
      {/* Back Button */}
      <div className="flex items-center space-x-2 text-blue-600 hover:text-blue-800">
        <ArrowLeft size={18} />
        <Link to="/returns" className="font-medium">
          Back to Return Requests
        </Link>
      </div>

      {/* Return Request Header */}
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between bg-white shadow-md rounded-2xl p-6 border border-gray-100">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">
            Return Request - {order.orderNumber}
          </h2>
          <p className="text-gray-500 text-sm mt-1">
            Requested At: {new Date(order.returnRequestedAt).toLocaleString()}
          </p>
        </div>
        <div className="mt-4 md:mt-0">
          <p className="text-3xl font-semibold text-green-600">
            ₹{order.totalAmount?.toLocaleString()}
          </p>
        </div>
      </div>

      {/* Customer Info */}
      <div className="bg-white shadow-sm rounded-xl p-6 border border-gray-100 space-y-3">
        <h3 className="text-lg font-semibold text-gray-700 border-b pb-2">
          Customer Info
        </h3>
        <InfoRow
          label="Name"
          value={`${order.user?.firstName || ""} ${order.user?.lastName || ""}`}
        />
        <InfoRow label="Email" value={order.user?.email || "N/A"} />
        <InfoRow label="Phone" value={order.user?.phone || "N/A"} />
      </div>

      {/* Return Status & Shipping Address */}
      <div className="grid md:grid-cols-2 gap-6">
        <div className="bg-white shadow-sm rounded-xl p-6 border border-gray-100 space-y-3">
          <h3 className="text-lg font-semibold text-gray-700 border-b pb-2">
            Return Status
          </h3>
          <InfoRow label="Status" value={order.returnStatus} />
          <InfoRow
            label="Payment Status"
            value={order.paymentStatus || "N/A"}
          />
          <InfoRow
            label="Payment Method"
            value={order.paymentMethod || "N/A"}
          />
        </div>

        <div className="bg-white shadow-sm rounded-xl p-6 border border-gray-100 space-y-3">
          <h3 className="text-lg font-semibold text-gray-700 border-b pb-2">
            Shipping Address
          </h3>
          <InfoRow
            label="Name"
            value={`${order.address?.firstName || ""} ${
              order.address?.lastName || ""
            }`}
          />
          <InfoRow label="Company" value={order.address?.company || "N/A"} />
          <InfoRow
            label="Address"
            value={
              order.address
                ? [
                    order.address.addressLine1,
                    order.address.addressLine2,
                    order.address.city,
                    order.address.state,
                    order.address.postalCode,
                    order.address.country,
                  ]
                    .join(" ")
                    .split(" ")
                    .reduce((acc, word, idx) => {
                      const lineIndex = Math.floor(idx / 4);
                      if (!acc[lineIndex]) acc[lineIndex] = [];
                      acc[lineIndex].push(word);
                      return acc;
                    }, [])
                    .map((lineWords, idx) => (
                      <span key={idx} className="block">
                        {lineWords.join(" ")}
                      </span>
                    ))
                : "N/A"
            }
          />

          <InfoRow label="Phone" value={order.address?.phone || "N/A"} />
        </div>
      </div>

      {/* Products */}
      <div className="bg-white shadow-sm rounded-xl p-6 border border-gray-100">
        <h3 className="text-lg font-semibold text-gray-700 border-b pb-3">
          Products
        </h3>
        <ul className="list-disc pl-5 mt-3 space-y-1">
          {order.items?.map((item) => (
            <li key={item.id}>
              {item.productName} - Qty: {item.quantity} - ₹
              {item.price?.toLocaleString()}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

// Small helper component for info rows
const InfoRow = ({ label, value }) => (
  <div className="flex justify-between text-sm text-gray-700">
    <span className="font-medium text-gray-600">{label}:</span>
    <span className="text-gray-800">{value}</span>
  </div>
);

export default ReturnDetails;
