"use client";

import React, { useEffect, useState } from "react";
import { RootState } from "../../../../store";
import { useDispatch, useSelector } from "react-redux";
import { onGoingBids } from "../../../../api/api";
import { useParams } from "next/navigation";
import { formatDate } from "../../../../common/DateFormant";
// import { formatCurrencyUSD } from "../../../../utils/commonFunction";
import Image from "next/image";
import { convertCurrency } from "@/src/utils/convertCurrency";

const ListingBids: React.FC = () => {
  const dispatch = useDispatch<any>();
  const params = useParams();
  const id = params?.id as string;

  const rates = useSelector(
    (state: RootState) => state.CurrencyExchangeRateReducer.rates
  );
  const currency = useSelector(
    (state: any) => state.CurrencyReducer.selectedCurrency
  );
  const { BidsData } = useSelector((state: RootState) => state.OnGoingReducer);
  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const [activeTab, setActiveTab] = useState<"bids" | "increments">("bids");

  useEffect(() => {
    if (id) {
      dispatch(onGoingBids(id));
    }
  }, [dispatch, id]);

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

  return (
    <div className="bg-gray-50 xs:p-0 md:p-4">
      <div className="max-w-6xl mx-auto">
        {/* Listing Card */}
        {BidsData?.data?.listing && (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-8">
            <div className="flex flex-col md:flex-row">
              {/* Image */}
              <div className="md:w-1/3 p-6 flex justify-center bg-gray-50">
                {BidsData?.data?.listing?.images?.[0] && (
                  <Image
                    unoptimized
                    src={BidsData.data.listing.images[0]}
                    alt={BidsData.data.listing.product_name || "Listing image"}
                    width={400}
                    height={256}
                    className="w-full h-64 object-contain rounded-lg"
                  />
                )}
              </div>

              {/* Details */}
              <div className="md:w-2/3 p-2 md:p-8">
                <div className="flex justify-between items-start">
                  <div>
                    <h1 className="text-lg md:text-3xl font-bold text-gray-900 mb-2 capitalize text-start">
                      {BidsData?.data?.listing?.product_name ||
                        "Unnamed Product"}
                    </h1>
                    <div className="flex items-center space-x-4 mb-4">
                      <span className="inline-flex items-center px-3 py-1 rounded-md bg-blue-50 text-blue-700 text-sm font-medium">
                        Active Auction
                      </span>
                      <span className="text-gray-500 text-sm">
                        {BidsData?.data?.bids?.length || 0} bids placed
                      </span>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-gray-500 text-sm">Ends in</p>
                    <p className="text-sm md:text-lg font-semibold text-gray-800">
                      {formatDate(BidsData?.data?.listing?.auction_ends_at)}
                    </p>
                  </div>
                </div>

                <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <p className="text-gray-500 text-sm text-center">
                      Current Bid
                    </p>
                    <p className="text-2xl font-bold text-gray-900 flex flex-col justify-center items-center">
                      {BidsData?.data?.listing?.currency === "CAD"
                        ? "C$"
                        : BidsData?.data?.listing?.currency === "USD"
                        ? "US$"
                        : ""}{" "}
                      {/* {BidsData?.data?.listing?.bids[0]?.amount || "0"} */}
                      {BidsData?.data?.listing?.bids.length > 0
                        ? new Intl.NumberFormat("en-US", {
                            minimumFractionDigits: 2,
                            useGrouping: true,
                          }).format(BidsData?.data?.listing?.bids[0]?.amount)
                        : "0"}
                      {currency !== BidsData?.data?.listing?.currency && (
                        <span className="text-gray-400 text-sm text-right">
                          ({" "}
                          {BidsData?.data?.listing?.currency === "USD"
                            ? "C$"
                            : "US$"}{" "}
                          {convertCurrency(
                            parseFloat(
                              Number(
                                BidsData?.data?.listing?.bids[0]?.amount
                              ).toFixed(3)
                            ),
                            BidsData?.data?.listing?.currency,
                            BidsData?.data?.listing?.currency === "USD"
                              ? "CAD"
                              : "USD",
                            rates
                          ).toFixed(2)}{" "}
                          )
                        </span>
                      )}
                    </p>
                  </div>
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <p className="text-gray-500 text-sm text-center">
                      Starting Price
                    </p>
                    <p className="text-xl font-bold text-gray-900 flex flex-col justify-center items-center">
                      {/* ${BidsData?.data?.listing?.starting_bid || "0"} */}
                      {BidsData?.data?.listing?.currency === "CAD"
                        ? "C$"
                        : BidsData?.data?.listing?.currency === "USD"
                        ? "US$"
                        : ""}{" "}
                      {BidsData?.data?.listing?.starting_bid
                        ? new Intl.NumberFormat("en-US", {
                            minimumFractionDigits: 2,
                            useGrouping: true,
                          }).format(BidsData?.data?.listing?.starting_bid)
                        : "0"}
                      {currency !== BidsData?.data?.listing?.currency && (
                        <span className="text-gray-400 text-sm text-right">
                          ({" "}
                          {BidsData?.data?.listing?.currency === "USD"
                            ? "C$"
                            : "US$"}{" "}
                          {convertCurrency(
                            parseFloat(
                              Number(
                                BidsData?.data?.listing?.starting_bid
                              ).toFixed(3)
                            ),
                            BidsData?.data?.listing?.currency,
                            BidsData?.data?.listing?.currency === "USD"
                              ? "CAD"
                              : "USD",
                            rates
                          ).toFixed(2)}{" "}
                          )
                        </span>
                      )}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Tabs */}
        <div className="flex gap-4 mb-4">
          <button
            onClick={() => setActiveTab("bids")}
            className={`px-4 py-2 rounded-sm text-sm font-medium ${
              activeTab === "bids"
                ? "bg-yellow-400 text-white"
                : "bg-gray-200 text-gray-600"
            }`}
          >
            Bid History
          </button>
          <button
            onClick={() => setActiveTab("increments")}
            className={`px-4 py-2 rounded-sm text-sm font-medium ${
              activeTab === "increments"
                ? "bg-yellow-400 text-white"
                : "bg-gray-200 text-gray-600"
            }`}
          >
            Price Increments
          </button>
        </div>

        {/* Bid History */}
        {activeTab === "bids" && (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="p-6 border-b border-gray-100">
              <h2 className="text-xl font-bold text-gray-900">Bid History</h2>
            </div>
            <div className="divide-y divide-gray-100 max-h-56 overflow-y-auto">
              {BidsData?.data?.bids?.length > 0 ? (
                BidsData.data.bids.map((bid: any) => (
                  <div
                    key={bid.id}
                    className="p-6 hover:bg-gray-50 transition-colors"
                  >
                    <div className="grid md:grid-cols-3 xs:grid-cols-1 gap-4 items-center">
                      <div className="flex gap-2 items-center">
                        <p className="text-lg font-semibold text-green-500">
                          {bid?.user?.phone
                            ? `**${bid.user.phone.slice(-2)}`
                            : "N/A"}
                        </p>
                      </div>
                      <div>
                        <p className="text-base text-gray-500">
                          Placed on {formatDate(bid?.created_at)}
                        </p>
                      </div>
                      <div className="text-lg font-bold flex flex-col justify-center items-center text-navy md:text-center xs:text-start">
                        {/* {formatCurrencyUSD(bid?.amount)} */}
                        {BidsData?.data?.listing?.currency === "CAD"
                          ? "C$"
                          : BidsData?.data?.listing?.currency === "USD"
                          ? "US$"
                          : ""}{" "}
                        {new Intl.NumberFormat("en-US", {
                          minimumFractionDigits: 2,
                          useGrouping: true,
                        }).format(bid?.amount)}
                        {currency != BidsData?.data?.listing?.currency && (
                          <span className="text-gray-400 text-sm text-right">
                            ({" "}
                            {BidsData?.data?.listing?.currency === "USD"
                              ? "C$"
                              : "US$"}{" "}
                            {convertCurrency(
                              parseFloat(Number(bid?.amount).toFixed(3)),
                              BidsData?.data?.listing?.currency,
                              BidsData?.data?.listing?.currency === "USD"
                                ? "CAD"
                                : "USD",
                              rates
                            ).toFixed(2)}{" "}
                            )
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="p-8 text-center">
                  <div className="mx-auto w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                    <svg
                      className="w-10 h-10 text-gray-400"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="1.5"
                        d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
                      />
                    </svg>
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 mb-1">
                    No bids yet
                  </h3>
                  <p className="text-gray-500">Be the first to place a bid!</p>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Price Increment Table */}
        {activeTab === "increments" && (
          <div className="p-6 bg-white rounded-sm border border-gray-100 shadow-sm overflow-hidden max-h-[20rem] mx-auto">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-lg font-semibold text-gray-800">
                Bid Increments
              </h2>
              <div className="text-sm text-gray-500">
                Last updated: {new Date().toLocaleDateString()}
              </div>
            </div>

            {/* Scrollable Table */}
            <div className="rounded-lg border border-gray-100 h-[15rem] overflow-y-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50 sticky top-0 z-10">
                  <tr>
                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                      #
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Price Range
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Increment
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {incrementData?.data?.increments?.map(
                    (item: any, index: number) => (
                      <tr
                        key={item.id}
                        className="hover:bg-gray-50 transition-colors"
                      >
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-center font-medium text-gray-900">
                          {index + 1}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          <div className="flex items-center">
                            <span className="font-medium">
                              {BidsData?.data?.listing?.currency === "CAD"
                                ? "C$"
                                : BidsData?.data?.listing?.currency === "USD"
                                ? "US$"
                                : ""}{" "}
                              {item.min_price}
                            </span>

                            <span className="mx-2 text-gray-300">-</span>
                            <span>
                              {item.max_price
                                ? `${
                                    BidsData?.data?.listing?.currency === "CAD"
                                      ? "C$"
                                      : BidsData?.data?.listing?.currency ===
                                        "USD"
                                      ? "US$"
                                      : ""
                                  } ${item.max_price}`
                                : "Above"}
                            </span>
                          </div>
                          {currency !== BidsData?.data?.listing?.currency && (
                            <div className="flex items-center">
                              <span className="text-gray-400 text-sm text-right">
                                ({" "}
                                {BidsData?.data?.listing?.currency === "USD"
                                  ? "C$"
                                  : "US$"}{" "}
                                {convertCurrency(
                                  parseFloat(Number(item.min_price).toFixed(3)),
                                  BidsData?.data?.listing?.currency,
                                  BidsData?.data?.listing?.currency === "USD"
                                    ? "CAD"
                                    : "USD",
                                  rates
                                ).toFixed(2)}{" "}
                                )
                              </span>
                              <span className="mx-2 text-gray-300">-</span>
                              <span>
                                {item.max_price ? (
                                  <>
                                    ({" "}
                                    {BidsData?.data?.listing?.currency === "USD"
                                      ? "C$"
                                      : "US$"}
                                    {convertCurrency(
                                      parseFloat(
                                        Number(item.max_price).toFixed(3)
                                      ),
                                      BidsData?.data?.listing?.currency,
                                      BidsData?.data?.listing?.currency ===
                                        "USD"
                                        ? "CAD"
                                        : "USD",
                                      rates
                                    ).toFixed(2)}{" "}
                                    )
                                  </>
                                ) : (
                                  "Above"
                                )}
                              </span>
                            </div>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-right flex flex-col justify-end items-end gap-y-1">
                          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            +{" "}
                            {BidsData?.data?.listing?.currency === "CAD"
                              ? "C$"
                              : BidsData?.data?.listing?.currency === "USD"
                              ? "US$"
                              : ""}{" "}
                            {item.increment}
                          </span>
                          {currency !== BidsData?.data?.listing?.currency && (
                            <span className="text-gray-400 text-xs text-right">
                              + ({" "}
                              {BidsData?.data?.listing?.currency === "USD"
                                ? "C$"
                                : "US$"}{" "}
                              {convertCurrency(
                                parseFloat(Number(item.increment).toFixed(3)),
                                BidsData?.data?.listing?.currency,
                                BidsData?.data?.listing?.currency === "USD"
                                  ? "CAD"
                                  : "USD",
                                rates
                              ).toFixed(2)}{" "}
                              )
                            </span>
                          )}
                        </td>
                      </tr>
                    )
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ListingBids;
