"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";

type Props = {
  currentUserID: number;
  reservePrice: number;
  orderGenerateData: any;
  ongoingData: any;
  SellerUserId: any;
  onClose?: () => void;
};

export default function AuctionResultPopup({
  currentUserID,
  reservePrice,
  orderGenerateData,
  ongoingData,
  SellerUserId,
  onClose,
}: Props) {
  const router = useRouter();
  const topBid = ongoingData?.data?.bids?.[0];
  const topBidUserId = topBid?.user?.id;
  const topBidAmount = topBid?.amount ?? 0;
  const buyerId = orderGenerateData?.order?.buyer_id;

  const isOrderDirectlyGeneratedByOtherUser =
    !!buyerId && buyerId !== currentUserID;

  let content = null;

  if (reservePrice) {
    // === CASE 1: Buyer placed order directly (and it's you)
    if (buyerId && buyerId === currentUserID) {
      content = (
        <>
          <h2 className="text-2xl font-bold text-center mb-4 text-black">
            🎉 Congratulations! 🎉
          </h2>
          <p className="mb-2 text-black">Order placed successfully</p>
          <p className="font-semibold mb-2 text-left text-black">
            Next Steps for Transfer:
          </p>
          <ul className="list-disc list-inside mb-4 text-left">
            <li className="text-black">
              <span className="font-bold text-black">Confirm Transfer:</span>{" "}
              Connect with the seller to confirm the purchase details.
            </li>
            <li className="text-black">
              <span className="font-bold text-black">Coordinate Transfer:</span>{" "}
              Arrange pickup/delivery of the purchased item. Contact our support
              team for assistance.
            </li>
            <li className="text-black">
              <span className="font-bold text-black">Documentation:</span>{" "}
              Complete any required documentation for the transfer.
            </li>
          </ul>
          <p className="mb-4 text-black">
            If you need further assistance, feel free to contact us by
            generating a ticket.
          </p>
        </>
      );
    }

    // === CASE 2: Buyer placed order directly (someone else)
    else if (isOrderDirectlyGeneratedByOtherUser) {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-blue-600">
            🔓 Order Unlocked
          </h2>
          <p className="text-gray-700 text-lg">
            Another user has unlocked the product and placed the order directly.
          </p>
        </>
      );
    }

    // === CASE 3: Top bidder won (meets reserve)
    else if (topBidUserId === currentUserID && topBidAmount >= reservePrice) {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-green-600">
            🎉 Congratulations!
          </h2>
          <p className="text-gray-700 text-lg">
            You can track your order and seller details in the <b>"Purchased"</b> section. in your Dashboard.
          </p>
        
        </>
      );
    }

    // === CASE 4: Top bidder didn't meet reserve
    else if (topBidUserId === currentUserID && topBidAmount < reservePrice) {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-yellow-500">
            Reserve Price Not Met
          </h2>
          <p className="text-gray-700 text-lg">
            You had the highest bid, but the seller's reserve price was not met.
            <br /> Your order was not generated.
          </p>
        </>
      );
    }

    // === CASE 5: You placed a bid but didn’t win
    else if (
      ongoingData?.data?.bids?.some(
        (bid: any) => bid.user?.id === currentUserID
      )
    ) {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-red-600">
            Auction Ended
          </h2>
          <p className="text-gray-700 text-lg">
            Unfortunately, you didn't win this time.
          </p>
        </>
      );
    }
  } else {
    // === CASE 6: You are the seller
    if (SellerUserId === currentUserID) {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-blue-600">
            Auction Ended
          </h2>
          <p className="text-gray-700 text-lg">
            Your Listed auction has ended. You can view the top bid and take next
            steps if needed.
          </p>
        </>
      );
    }

    // === CASE 7: You are the winning top bidder
    else if (topBidUserId === currentUserID) {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-green-600">
            🎉 Congratulations!
          </h2>
          <p className="text-gray-700 text-lg">
            You can track your order and seller details in the <b>"Purchased"</b> section. in your Dashboard.
          </p>
          <div className="flex flex-row gap-4 justify-center mt-4">
            <button
              onMouseEnter={() => router.prefetch("/profile/listing")}
              onClick={() => router.push("/profile/listing")}
              className="px-6 py-2 bg-blue-600 text-white rounded-xl text-sm hover:bg-blue-700 transition-all"
            >
              Track Order
            </button>
            <button
              onClick={() => onClose?.()}
              className="px-6 py-2 bg-gray-800 text-white rounded-xl text-sm hover:bg-[#F8CB1F] transition-all"
            >
              Close
            </button>
          </div>
        </>
      );
    }

    // === CASE 8: You didn’t win
    else {
      content = (
        <>
          <h2 className="text-3xl font-extrabold text-red-600">
            Auction Ended
          </h2>
          <p className="text-gray-700 text-lg">
            Unfortunately, you didn't win this time.
          </p>
        </>
      );
    }
  }
  // Auto-close after 2 seconds if no content to show
  useEffect(() => {
    if (!content && onClose) {
      const timer = setTimeout(() => {

        onClose();
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [content, onClose]);

  // Don't render anything if there's no content
  if (!content) return null;

  // Determine if content already includes a Close button (for congrats cases)
  const isCongratsCase =
    (reservePrice && topBidUserId === currentUserID && topBidAmount >= reservePrice) ||
    (!reservePrice && topBidUserId === currentUserID);

  return (
    <div className="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 xs:p-2">
      <div className="bg-white rounded-2xl shadow-2xl p-8 max-w-md w-full text-center space-y-5">
        {content}
        {!isCongratsCase && (
          <button
            onClick={() => onClose?.()}
            className="mt-4 px-6 py-2 bg-gray-800 text-white rounded-xl text-sm hover:bg-[#F8CB1F] transition-all"
          >
            Close
          </button>
        )}
      </div>
    </div>
  );
}
