import { useState } from "react";
import { useGetReturnedOrdersQuery } from "../../../features/orders/ordersAPI";
import Table from "../../../components/common/Table";
import Pagination from "../../../components/common/Pagination";
import { Link } from "react-router-dom";

const ReturnHistory = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const perPage = 10;

  const { data, isLoading, isError } = useGetReturnedOrdersQuery({
    page: currentPage,
    limit: perPage,
  });

  if (isLoading) return <p className="text-gray-500">Loading...</p>;
  if (isError)
    return <p className="text-red-600">Failed to load return history.</p>;

  const returns = data?.data || [];
  const totalPages = Math.ceil((data?.count || 0) / perPage);

  const columns = [
    { key: "sr", label: "Sr. No", render: (_, __, i) => i + 1 },
    { key: "orderNumber", label: "Order Number" },
    {
      key: "customer",
      label: "Customer",
      render: (_, row) =>
        `${row.user?.firstName || ""} ${row.user?.lastName || ""}`,
    },
    {
      key: "totalAmount",
      label: "Total",
      render: (_, row) => `₹${row.totalAmount}`,
    },
    {
      key: "returnStatus",
      label: "Return Status",
      render: (_, row) => (
        <span
          className={`px-3 py-1 rounded-full text-xs font-medium ${
            row.returnStatus === "APPROVED"
              ? "bg-green-100 text-green-700"
              : "bg-gray-100 text-gray-600"
          }`}
        >
          {row.returnStatus}
        </span>
      ),
    },
    {
      key: "approvedAt",
      label: "Approved On",
      render: (_, row) =>
        row.updatedAt ? new Date(row.updatedAt).toLocaleDateString() : "-",
    },
  ];

  const rowActions = (row) => (
    <Link
      to={`/returns/${row.id}`}
      className="px-3 py-1 bg-blue-100 text-blue-600 rounded hover:bg-blue-200"
    >
      View
    </Link>
  );

  return (
    <div className="space-y-6">
      <h2 className="text-xl font-semibold text-gray-700">Return History</h2>
      <span className="text-sm bg-yellow-200 p-2 text-gray-500">
        Shows only
        {/* <span className="ml-1 text-yellow-600 font-medium">(Requested)</span>, */}
        <span className="ml-1 text-green-600 font-medium">Approved</span>,
        <span className="ml-1 text-red-600 font-medium">COMPLETED</span>
      </span>
      <Table columns={columns} data={returns} actions={rowActions} />

      <Pagination
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={setCurrentPage}
      />
    </div>
  );
};

export default ReturnHistory;
