"use client";

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../store";
import { bidsHistory } from "../../../api/api";
import Image from "next/image";
import Link from "next/link";
import TimeAgo from "../../../common/TimeAgo";
import { convertCurrency } from "../../../utils/convertCurrency";

export default function BidHistoryPage() {
  const dispatch = useDispatch<any>();
  const { data } = useSelector((state: RootState) => state.BidsHistoryReducer);
  const [currentPage, setCurrentPage] = useState(1);
  const currency = useSelector(
    (state: any) => state.CurrencyReducer.selectedCurrency
  );
  const rates = useSelector(
    (state: RootState) => state.CurrencyExchangeRateReducer.rates
  );
  const itemsPerPage = 2;

  useEffect(() => {
    dispatch(bidsHistory());
  }, [dispatch]);

  if (!data || !data.success) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <h1>Loading...</h1>
      </div>
    );
  }

  // Group bids by listing_id
  const bidsByListing: Record<number, any[]> = {};
  data?.data?.listings?.forEach((bid: any) => {
    if (!bidsByListing[bid?.listing_id]) {
      bidsByListing[bid?.listing_id] = [];
    }
    bidsByListing[bid?.listing_id].push(bid);
  });

  // Sort latest listings first by bid created_at
  const sortedListings = Object.entries(bidsByListing).sort(([, a], [, b]) => {
    return (
      new Date(b[0]?.created_at).getTime() -
      new Date(a[0]?.created_at).getTime()
    );
  });

  const totalPages = Math.ceil(sortedListings.length / itemsPerPage);
  const paginatedListings = sortedListings.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const formatAmount = (amount: string) => {
    const num = parseFloat(amount);
    return num % 1 === 0 ? num.toString() : num.toFixed(2);
  };

  const createSlug = (text: string) =>
    text
      ?.trim()
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, "")
      .replace(/\s+/g, "-")
      .replace(/-+/g, "-");

  return (
    <div className="container mx-auto px-4 py-8 max-w-7xl">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-gray-800">Your Bid History</h1>
        <div className="text-sm text-gray-500">
          Showing {data?.data?.listings?.length} bids across{" "}
          {Object.keys(bidsByListing).length} listings
        </div>
      </div>

      {data?.data?.listings?.length === 0 ? (
        <div className="text-center py-12 bg-white rounded-lg shadow-sm">
          <p className="text-gray-500 text-lg mb-4">
            You haven't placed any bids yet.
          </p>
        </div>
      ) : (
        <>
          <div className="space-y-8">
            {paginatedListings.map(([listingId, bids]) => {
              const listing = bids[0].listing;
              const sortedBids = [...bids].sort(
                (a, b) =>
                  new Date(b.created_at).getTime() -
                  new Date(a.created_at).getTime()
              );

              return (
                <div
                  key={Number(listingId)}
                  className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow"
                >
                  <div className="p-5">
                    <div className="flex flex-col md:flex-row gap-6">
                      {/* Image */}
                      <div className="w-full md:w-1/5">
                        <div className="relative aspect-square rounded-lg overflow-hidden bg-gray-100">
                          {Array.isArray(listing?.images) &&
                          listing?.images?.length > 0 ? (
                            <Image
                              unoptimized
                              src={listing?.images[0]}
                              alt={listing?.product_name}
                              fill
                              className="object-cover"
                              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                              priority
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-gray-400">
                              No Image
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Details */}
                      <div className="flex-1">
                        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                          <div>
                            <h2 className="text-xl font-semibold text-gray-800 capitalize">
                              {listing?.product_name}
                            </h2>
                            <div className="flex items-center gap-2 mt-1">
                              <span className="text-sm text-gray-500">
                                {listing?.category.name}
                              </span>
                              <span className="text-xs px-2 py-1 bg-blue-100 text-blue-800 rounded-full">
                                {listing?.product_type}
                              </span>
                            </div>
                          </div>
                        </div>

                        <div className="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
                          <div>
                            <p className="text-sm text-gray-500">Location</p>
                            <p className="text-gray-800">
                              {listing?.location}, {listing?.sub_location}
                            </p>
                          </div>
                        </div>

                        <div className="mt-4">
                          <h3 className="text-lg font-medium text-gray-800 mb-3">
                            Your Bids
                          </h3>
                          <div className="space-y-3 max-h-52 overflow-auto">
                            {sortedBids?.map((bid) => (
                              <div
                                key={bid.id}
                                className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                              >
                                <div>
                                  <p className="text-sm text-gray-500">
                                    Bid placed on{" "}
                                    <TimeAgo timestamp={bid.created_at} />
                                  </p>
                                  <div className="text-lg font-bold text-gray-800">
                                    <span>
                                      {formatAmount(bid?.amount)}{" "}
                                      {listing?.currency}
                                    </span>{" "}
                                    {currency != listing?.currency && (
                                      <span className="text-sm font-semibold text-gray-400">
                                        (
                                        {listing?.currency === "USD"
                                          ? "C$"
                                          : "US$"}{" "}
                                        {convertCurrency(
                                          parseFloat(bid?.amount),

                                          listing?.currency,
                                          listing?.currency === "USD"
                                            ? "CAD"
                                            : "USD",
                                          rates
                                        ).toFixed(2)}
                                        )
                                      </span>
                                    )}
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>

                        <div className="mt-6">
                          {listing?.expired == 0 ? (
                            <Link
                              href={`/auction/${listing.id}/${createSlug(
                                listing?.product_name
                              )}/${createSlug(listing?.category?.name)}`}
                              className="px-4 py-2 bg-yellow-400 hover:bg-gray-100 text-black rounded-lg text-sm font-medium transition-colors inline-block"
                            >
                              View Listing Details
                            </Link>
                          ) : (
                            <span className="px-4 py-2 bg-gray-100 text-gray-400 rounded-lg text-sm font-medium inline-block cursor-not-allowed">
                              Auction Expired
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Pagination */}
          <div className="flex justify-end items-center mt-8 gap-2">
            {/* Previous Button */}
            <button
              className={`px-4 py-2 rounded transition-colors ${
                currentPage === 1
                  ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                  : "bg-yellow-400 text-black hover:bg-yellow-500"
              }`}
              onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              Previous
            </button>

            {/* Next Button */}
            <button
              className={`px-4 py-2 rounded transition-colors ${
                currentPage === totalPages
                  ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                  : "bg-yellow-400 text-black hover:bg-yellow-500"
              }`}
              onClick={() =>
                setCurrentPage((prev) => Math.min(prev + 1, totalPages))
              }
              disabled={currentPage === totalPages}
            >
              Next
            </button>
          </div>
        </>
      )}
    </div>
  );
}
