"use client";

import React, { useEffect, useState } from "react";
import {
  priorityBids,
  priorityBidsData,
  priorityBidsUpdate,
  unlockPriorityBids,
  viewListing,
} from "../../../../api/api";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import { RootState } from "../../../../store";
import { FaCheckCircle } from "react-icons/fa";
import { ExclamationCircleIcon } from "@heroicons/react/24/outline";
import Swal from "sweetalert2";
import { useParams, useRouter } from "next/navigation";

function PriorityBids() {
  const dispatch = useDispatch<any>();
  const router = useRouter();
  const listingData = useSelector(
    (state: RootState) => state.viewListingReducer
  );
  const { priorityData } = useSelector(
    (state: RootState) => state.PriorityReducer
  );
  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const increments = incrementData?.data?.increments || [];

  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const params = useParams();
  const id = params?.id as string;
  const [isOpen, setIsOpen] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const [currentPrice, setCurrentPrice] = useState<number>(0);
  console.log("Current Price:", currentPrice);

  const [isLoading, setIsLoading] = useState(false);
  const [bid, setBid] = useState<string>("0.00");
  const [bidError, setBidError] = useState<string>("");
  const viewListingData = listingData?.data?.data?.listing;
  const listing_id = listingData?.data?.data?.listing?.id;
  const CurrentUserID = userData?.data?.user.id;
  const userID = viewListingData?.user_id;
  const priorityBidData = priorityData?.data;

  const TopBids =
    Number(listingData?.data?.data?.listing?.bids[0]?.amount) || 0;

  const priorityBidAmount =
    Number(priorityBidData?.priorityBid?.[0]?.amount) || 0;

  const isDisabled = priorityBidAmount > 0 && priorityBidAmount > TopBids;

  useEffect(() => {
    router.prefetch("/auth/login");
  }, [router]);

  useEffect(() => {
    if (priorityBidAmount) {
      setCurrentPrice(Number(priorityBidAmount));
      setBid(
        Number(priorityBidAmount).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })
      );
    } else if (viewListingData?.starting_bid) {
      setCurrentPrice(Number(viewListingData?.starting_bid));
      setBid(
        Number(viewListingData?.starting_bid).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })
      );
    }
  }, [viewListingData?.starting_bid, priorityBidAmount]);

  const getIncrement = (amount: number) => {
    const numericAmount = Number(amount);
    for (const range of increments) {
      const min = parseFloat(range.min_price);
      const max = range.max_price ? parseFloat(range.max_price) : Infinity;

      if (numericAmount >= min && numericAmount <= max) {
        return parseFloat(range.increment);
      }
    }
    return 0;
  };

  // const handleIncrement = () => {
  //   const numericBid = Number(bid.replace(/,/g, ""));
  //   const increment = getIncrement(numericBid);
  //   const newBid = numericBid + increment;
  //   setBid(
  //     newBid.toLocaleString(undefined, {
  //       minimumFractionDigits: 2,
  //       maximumFractionDigits: 2,
  //     })
  //   );
  // };

  // const handleDecrement = () => {
  //   const numericBid = Number(bid.replace(/,/g, ""));
  //   const increment = getIncrement(numericBid);
  //   const newBid = numericBid - increment;

  //   if (newBid >= currentPrice) {
  //     setBid(
  //       newBid.toLocaleString(undefined, {
  //         minimumFractionDigits: 2,
  //         maximumFractionDigits: 2,
  //       })
  //     );
  //   } else {
  //     setBid(
  //       currentPrice.toLocaleString(undefined, {
  //         minimumFractionDigits: 2,
  //         maximumFractionDigits: 2,
  //       })
  //     );
  //   }
  // };

  const handelSetPriority = () => {
    if (!CurrentUserID) {
      const formattedCategoryName = viewListingData?.category?.name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      const productName = viewListingData?.product_name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      const returnUrl = `/auction/${id}/${formattedCategoryName}/${productName}`;
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return;
    } else {
      setIsOpen(true);
    }
  };

  // const handleBidChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  //   let value = e.target.value;
  //   value = value.replace(/[^0-9.]/g, "");
  //   const parts = value.split(".");
  //   let integerPart = parts[0];
  //   let decimalPart = parts[1] || "";

  //   if (decimalPart.length > 2) {
  //     decimalPart = decimalPart.slice(0, 2);
  //   }

  //   integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

  //   const formatted = decimalPart
  //     ? `${integerPart}.${decimalPart}`
  //     : integerPart;
  //   setBid(formatted);
  // };

  // const handleBidBlur = () => {
  //   const numericBid = Number(bid.replace(/,/g, ""));
  //   if (!numericBid || numericBid < currentPrice) {
  //     setBid(
  //       currentPrice.toLocaleString(undefined, { minimumFractionDigits: 2 })
  //     );
  //   } else {
  //     setBid(
  //       numericBid.toLocaleString(undefined, {
  //         minimumFractionDigits: 2,
  //         maximumFractionDigits: 2,
  //       })
  //     );
  //   }
  // };

  const handelBidData = async (id: number, bid: string) => {
    setIsLoading(true);
    try {
      const numericBid = Number(bid.replace(/,/g, ""));
      const payload = {
        amount: numericBid,
        listing_id: id,
      };

      const alreadyPlaced = priorityBidData?.priorityBid?.length > 0;
      const response = alreadyPlaced
        ? await dispatch(priorityBidsUpdate(payload))
        : await dispatch(priorityBids(payload));

      if (response?.payload?.success === true) {
        const confirmedBid = response?.payload?.data?.amount ?? numericBid;

        setIsOpen(false);
        setShowSuccess(true);
        setBidError("");
        setBid(
          confirmedBid.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })
        );

        dispatch(priorityBidsData(viewListingData?.id));
      } else {
        const errorMessage =
          typeof response.payload === "string"
            ? response.payload
            : response?.payload?.error ||
              response?.payload?.message ||
              "Failed to submit bid.";

        Swal.fire({
          position: "center",
          icon: "error",
          title: errorMessage,
          confirmButtonText: "OK",
          showConfirmButton: true,
          timer: undefined,
          customClass: {
            title: "swal-title-custom",
            confirmButton: "swal-confirm-button",
          },
        });

        setBidError(errorMessage);
        setIsLoading(false);
      }
    } catch {
      setIsLoading(false);
      toast.error("Something went wrong. Please try again.");
    }
  };

  const handleIncreaseBid = () => {
    setIsOpen(true);
  };

  const handleClosePopup = () => {
    setBidError("");
    setIsOpen(false);
  };

  const handleSuccessPopup = () => {
    setShowSuccess(false);
    setIsLoading(false);
  };

  const handleUnlockPriceWithConfirmation = async (
    listingId: number,
    feeAmount: number
  ) => {
    if (!CurrentUserID) {
      const formattedCategoryName = viewListingData?.category?.name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      const productName = viewListingData?.product_name
        ?.replace(/[^a-zA-Z0-9\s]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();

      const returnUrl = `/auction/${id}/${formattedCategoryName}/${productName}`;
      router.push(`/auth/login?callbackUrl=${encodeURIComponent(returnUrl)}`);
      return;
    }

    const result = await Swal.fire({
      title: "Unlock Price",
      html: `
      <p>Are you sure you want to unlock the price to set a priority bid?</p>
      <p class="mt-2 font-semibold text-lg text-black">
        Unlock Fee: <span style="color:#F8CB1F;">₹${feeAmount}</span>
      </p>
    `,
      showCancelButton: true,
      confirmButtonText: "Unlock",
      cancelButtonText: "No",
      confirmButtonColor: "#04104E",
      cancelButtonColor: "#d33",
    });

    if (result.isConfirmed) {
      try {
        const res = await dispatch(unlockPriorityBids(listingId)).unwrap();
        // ✅ Show toast message from API response
        toast.success(
          res?.data?.message || "Priority bid unlocked successfully"
        );
        setBidError("");

        // 🔄 Refresh both listing + priority bid data
        dispatch(viewListing({ id: id, user_id: CurrentUserID }));
        dispatch(priorityBidsData(String(listingId)));
      } catch (err: any) {
        console.error("API Error:", err);

        // ❌ Show error toast
        toast.error(
          err?.message || "Failed to unlock priority bid. Please try again."
        );
      }
    }
  };

  useEffect(() => {
    if (listing_id && CurrentUserID) {
      dispatch(priorityBidsData(listing_id));
    }
  }, [dispatch, listing_id, CurrentUserID]);
  useEffect(() => {
    if (listingData?.data?.data?.listing?.priority_bid_exist) {
      const minBid = Math.max(
        Number(listingData?.data?.data?.listing?.top_priority_bid_amount || 0),
        Number(listingData?.data?.data?.listing?.max_bid_required || 0)
      );

      setCurrentPrice(minBid);
      setBid(
        minBid.toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })
      );
    } else if (viewListingData?.starting_bid) {
      setCurrentPrice(Number(viewListingData?.starting_bid));
      setBid(
        Number(viewListingData?.starting_bid).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })
      );
    }
  }, [viewListingData?.starting_bid, listingData]);

  return (
    <div className="container mx-auto p-4 bg-white rounded-md mt-4 xs:max-w-full">
      <div className="border rounded-md p-4 bg-white shadow-sm">
        {priorityBidData?.priorityBid?.length > 0 ? (
          <>
            <div className="bg-green-100 text-green-800 px-4 py-2 rounded flex items-center mb-3">
              <svg
                className="w-5 h-5 mr-2 text-green-600"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.707a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414L9 13.414l4.707-4.707z"
                  clipRule="evenodd"
                />
              </svg>
              <div className="font-medium text-black">
                {priorityBidData.priorityBid.map((data: any) => (
                  <div key={data.id}>Bidding up to: {data.amount}</div>
                ))}
              </div>
            </div>

            <div className="flex items-start">
              <button
                onClick={handleIncreaseBid}
                className="border bg-navy text-white font-semibold px-4 py-2 rounded mb-3"
              >
                Increase Bid
              </button>
            </div>

            <p className="text-gray-600 text-sm text-start">
              Following the auction live is an easy way to make sure you stay
              the highest bidder.
            </p>
          </>
        ) : (
          <>
            <p className="text-lg text-black text-start mb-5">
              Don&apos;t miss getting what you need. Set a priority bid to stay
              ahead—your bid automatically increases until your max limit is
              reached!
            </p>

            <button
              className={`md:custom-button-price xs:custom-button-sm ${
                CurrentUserID === userID || viewListingData?.expired == 1
                  ? "pointer-events-none opacity-50"
                  : ""
              }`}
              onClick={(e) => {
                if (CurrentUserID === userID || viewListingData?.expired == 1) {
                  e.preventDefault();
                  return;
                }
                handelSetPriority();
              }}
            >
              <span className="relative text-black z-10 xs:text-xs font-semibold md:text-[1rem]">
                Place Priority Bid
              </span>
            </button>
          </>
        )}
      </div>

      {isOpen && (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50 xs:p-2">
          <div className="w-full md:max-w-2xl xs:max-w-lg bg-gray-100 md:p-8 xs:p-2 rounded-xl shadow-lg relative">
            <button
              onClick={() => handleClosePopup()}
              className="absolute top-0 md:right-3 cursor-pointer xs:right-3 text-black hover:text-gray-800 text-4xl font-normal p-0"
            >
              &times;
            </button>
            <p className="text-gray-800 font-bold mb-4 text-2xl text-center">
              Set Priority Bid
            </p>
            {listingData?.data?.data?.listing?.priority_bid_exist &&
              !listingData?.data?.data?.listing?.priority_unlocked == false && (
                <>
                  {!(priorityBidAmount > 0 && priorityBidAmount > TopBids) && (
                    <p className="text-sm mb-4 text-red-600 text-center font-bold">
                      Maximum Priority Bid:{" "}
                      {viewListingData?.currency === "CAD"
                        ? "C$"
                        : viewListingData?.currency === "USD"
                        ? "$"
                        : ""}
                      {Math.max(
                        Number(
                          listingData?.data?.data?.listing
                            ?.top_priority_bid_amount || 0
                        ),
                        Number(
                          listingData?.data?.data?.listing?.max_bid_required ||
                            0
                        )
                      )}
                      <br />
                      Place a higher bid to become the top bidder
                    </p>
                  )}
                </>
              )}
            {!listingData?.data?.data?.listing?.priority_bid_exist && (
              <label className="block text-gray-700 font-semibold mb-3 text-lg text-center">
                Bid up to
              </label>
            )}

            {(!listingData?.data?.data?.listing?.priority_bid_exist ||
              listingData?.data?.data?.listing?.priority_unlocked) && (
              <>
                <div className="flex justify-center items-center gap-4">
                  {/* Decrement Button */}
                  <button
                    onClick={() => {
                      const numericBid = Number(bid.replace(/,/g, ""));
                      const increment = getIncrement(numericBid);

                      let newBid = numericBid - increment;

                      // Minimum bid based on priority logic
                      if (
                        listingData?.data?.data?.listing?.priority_bid_exist
                      ) {
                        const minBid = Math.max(
                          Number(
                            listingData?.data?.data?.listing
                              ?.top_priority_bid_amount || 0
                          ),
                          Number(
                            listingData?.data?.data?.listing
                              ?.max_bid_required || 0
                          )
                        );
                        if (newBid < minBid) newBid = minBid;
                      } else {
                        const startingBid = Number(
                          viewListingData?.starting_bid || 0
                        );
                        if (newBid < startingBid) newBid = startingBid;
                      }

                      setBid(
                        newBid.toLocaleString(undefined, {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })
                      );
                    }}
                    className="md:px-5 md:py-3 xs:px-3 xs:py-1 bg-gray-300 border border-gray-300 rounded-lg text-2xl font-bold"
                  >
                    -
                  </button>

                  {/* Bid Input */}
                  <div className="relative flex items-center border border-gray-300 rounded-lg bg-white">
                    <span className="px-3 py-3 text-lg font-semibold text-gray-600 border-r border-gray-300">
                      {viewListingData?.currency === "CAD"
                        ? "C$"
                        : viewListingData?.currency === "USD"
                        ? "$"
                        : ""}
                    </span>
                    <input
                      type="text"
                      value={bid}
                      onChange={(e) => {
                        // Allow only numbers and dot
                        const value = e.target.value.replace(/[^0-9.]/g, "");
                        setBid(value);
                      }}
                      onBlur={() => {
                        let numericBid = Number(bid.replace(/,/g, ""));
                        let minBid = Number(viewListingData?.starting_bid || 0);

                        if (
                          listingData?.data?.data?.listing?.priority_bid_exist
                        ) {
                          minBid = Math.max(
                            Number(
                              listingData?.data?.data?.listing
                                ?.top_priority_bid_amount || 0
                            ),
                            Number(
                              listingData?.data?.data?.listing
                                ?.max_bid_required || 0
                            )
                          );
                        }

                        if (numericBid < minBid) numericBid = minBid;

                        setBid(
                          numericBid.toLocaleString(undefined, {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2,
                          })
                        );
                      }}
                      className="flex-1 text-center p-3 text-xl font-medium outline-none bg-transparent border-none xs:w-[50%]"
                    />
                  </div>

                  {/* Increment Button */}
                  <button
                    onClick={() => {
                      const numericBid = Number(bid.replace(/,/g, ""));
                      const increment = getIncrement(numericBid);
                      const newBid = numericBid + increment;

                      setBid(
                        newBid.toLocaleString(undefined, {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })
                      );
                    }}
                    className="md:px-5 md:py-3 xs:px-3 xs:py-1 bg-gray-300 border border-gray-300 rounded-lg text-2xl font-bold"
                  >
                    +
                  </button>
                </div>
              </>
            )}

            {bidError && (
              <div className="flex justify-center items-center mt-3 gap-4">
                <div className="w-8 h-8 bg-red-500 rounded-sm flex items-center justify-center">
                  <ExclamationCircleIcon className="w-5 h-5 text-white" />
                </div>
                <div className="text-red-600 text-lg font-semibold w-[60%] text-left">
                  {bidError}
                </div>
              </div>
            )}
            {(!listingData?.data?.data?.listing?.priority_bid_exist ||
              listingData?.data?.data?.listing?.priority_unlocked) && (
              <div>
                <button
                  onClick={() => handelBidData(viewListingData?.id, bid)}
                  disabled={isDisabled || isLoading}
                  className="mt-6 bg-navy hover:bg-navy text-white font-bold py-4 rounded-lg text-xl w-full 
             disabled:bg-gray-400 disabled:text-white disabled:cursor-not-allowed overflow-auto"
                >
                  {isLoading ? (
                    <span className="loader"></span>
                  ) : (
                    <>
                      Bid up to {bid}{" "}
                      {viewListingData?.currency === "CAD"
                        ? "C$"
                        : viewListingData?.currency === "USD"
                        ? "$"
                        : ""}
                    </>
                  )}
                </button>

                <p className="text-base text-gray-700 mt-4 text-center">
                  Bids are binding and cannot be retracted. If your bid
                  doesn&apos;t meet our bidding increments, we&apos;ll round it
                  down to the right amount.
                </p>
              </div>
            )}
            {/* ✅ Unlock section: only show if priority bid exists */}
            {listingData?.data?.data?.listing?.priority_bid_exist &&
            !listingData?.data?.data?.listing?.priority_unlocked ? (
              <div className="mt-6 text-red-600 font-bold text-center border-t pt-4">
                <p className="text-sm mb-4">
                  This listing already has a Priority Bid from another user.
                  Take the lead and win — unlock the Maximum Priority Bid for
                  just {incrementData?.data?.auctionFee[0]?.priority_unlock_fee}{" "}
                  and place a higher bid
                </p>

                <button
                  onClick={() =>
                    handleUnlockPriceWithConfirmation(
                      viewListingData?.id,
                      incrementData?.data?.auctionFee[0]?.priority_unlock_fee
                    )
                  }
                  className="bg-yellow-400 hover:bg-yellow-500 text-black font-semibold py-3 px-6 rounded-lg"
                >
                  Take Your Chance — Unlock for{" "}
                  {incrementData?.data?.auctionFee[0]?.priority_unlock_fee}
                </button>
              </div>
            ) : null}
          </div>
        </div>
      )}

      {showSuccess && (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50 xs:p-2">
          <div className="bg-white max-w-lg w-full text-center shadow-lg relative">
            <div className="bg-green-100 py-6">
              <div className="flex justify-center mb-4">
                <FaCheckCircle size={40} color="green" />
              </div>
              <h2 className="text-2xl font-bold text-gray-900 mb-2">
                Bidding up to {bid}{" "}
                {viewListingData?.currency === "CAD"
                  ? "CAD"
                  : viewListingData?.currency === "USD"
                  ? "USD"
                  : ""}
              </h2>
            </div>
            <div className="py-6 px-3">
              <p className="text-gray-700 mb-6">
                We&apos;ll bid up to this amount on the day of the auction.{" "}
                <br />
                You&apos;ll receive email updates if you&apos;re outbid before
                the lot opens for live sale.
              </p>
              <div className="flex justify-center gap-4">
                <button
                  onClick={handleSuccessPopup}
                  className="bg-orange-500 text-white font-semibold px-6 py-2 rounded hover:bg-orange-600"
                >
                  Done
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default PriorityBids;
