"use client";

import React, { useEffect, useState } from "react";
import { RootState } from "../../../store";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { useParams, useRouter } from "next/navigation";
import { formatDate } from "../../../common/DateFormant";
import { tracklistings } from "../../../api/api";
import ImageModal from "../../../components/bayerProfile/pages/components/ImageModal";
import { convertCurrency } from "../../../utils/convertCurrency";
import Image from "next/image";
import ClientShareButtons from "../../../components/ClientShareButtons";
import { DateTime } from "luxon";
import safeParseTime from "../../../utils/dateUtils";
import profileLocation from "../../../assets/profileLocation.svg";

const AuctionInfo: React.FC = () => {
  const dispatch = useDispatch<any>();
  const router = useRouter();
  const params = useParams();
  const id = params?.id as string;
  const productName = params?.productName as string;
  const productCategoryName = params?.categoryName as string;
  const { trackListData, loading: trackLoading } = useSelector(
    (state: RootState) => state.AllListingReducer
  );
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const settings = homedata?.data?.settings;
  const userTimeZone = settings?.default_timezone || "UTC";
  const viewListingData = trackListData?.data?.listing;

  const [selectedImage, setSelectedImage] = useState(
    viewListingData?.images?.[0]
  );
  const [isModalOpens, setIsModalOpens] = useState(false);
  const [auctionEnded, setAuctionEnded] = useState(false);

  const domainUrl = process.env.NEXT_PUBLIC_PRODUCT_URL!;
  const rates = useSelector(
    (state: RootState) => state.CurrencyExchangeRateReducer.rates
  );
  const currency = useSelector(
    (state: any) => state.CurrencyReducer.selectedCurrency
  );
  const closeModal = () => {
    setIsModalOpens(false); // Close modal
  };

  useEffect(() => {
    const routesToPrefetch = [
      "/profile/chat",
      "/profile/wallet/transaction/",
      "/profile/listing",
      "/",
    ];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  const handleImageClick = (image: string) => {
    setSelectedImage(image);
    setIsModalOpens(true);
  };

  const productUrl = `${domainUrl}/auction/${id}/${productCategoryName}/${productName}`;
  const metaTitle = viewListingData?.product_name || "Auction Item";
  const metaDescription =
    viewListingData?.description?.substring(0, 160) ||
    "Check out this amazing auction item!";

  const handleCarfax = async () => {
    const vin = viewListingData.vin_number.trim();
    await navigator.clipboard.writeText(vin);
    try {
      const country = viewListingData?.location;
      if (country === "Canada") {
        window.open(
          `https://www.carfax.ca/tools/vin-decode/vin-decode-results?vin=${vin}`,
          "_blank"
        );
      } else {
        await navigator.clipboard.writeText(vin);
        window.open(
          "https://www.carfax.com/vehicle-history-reports/",
          "_blank"
        );
      }
    } catch (error) {
      console.log(error);

      alert("Could not determine your location. Opening default Carfax.");
      window.open(
        `https://www.carfax.ca/tools/vin-decode/vin-decode-results?vin=${vin}`,
        "_blank"
      );
    }
  };
  //

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

  useEffect(() => {
    setAuctionEnded(false);
  }, [id]);

  // Fix the useEffect call

  useEffect(() => {
    setSelectedImage(viewListingData?.images[0]);
  }, [viewListingData]);

  const selectedIndex = viewListingData?.images.indexOf(selectedImage) || 0;
  const currentTime = safeParseTime(
    settings?.current_time_formatted,
    "yyyy-MM-dd HH:mm:ss",
    userTimeZone
  );

  const auctionStartTime = viewListingData?.start_datetime
    ? DateTime.fromISO(viewListingData?.start_datetime.replace(" ", "T"), {
        zone: userTimeZone,
      })
    : null;

  const isComingSoon = auctionStartTime && auctionStartTime > currentTime;

  useEffect(() => {
    if (typeof window !== "undefined" && viewListingData?.images?.length) {
      viewListingData.images.forEach((imgUrl: string) => {
        const preloadImg = new window.Image();
        preloadImg.src = imgUrl;
      });
    }
  }, [viewListingData?.images]);

  return (
    <>
      <div className="max-w-7xl m-auto">
        <div className="lg:grid lg:grid-cols-12 gap-4 pt-6 xs:flex xs:flex-col-reverse">
          <div className="xl:col-span-4 lg:col-span-4 xs:col-span-12 lg:p-0 xs:p-4 flex flex-col">
            {/* Bids summary card */}
            <div className="container mx-auto p-4 bg-white rounded-md mt-4 xs:max-w-full">
              <h2 className="text-2xl text-black font-bold mb-3 text-start">
                Auction bids
              </h2>

              {trackLoading ? (
                <div className="flex justify-center items-center">
                  <div className="loader2"></div>
                </div>
              ) : trackListData?.data?.listing ? (
                <div className="text-start text-gray-800 grid gap-1">
                  {}{" "}
                  {trackListData.data.listing.top_bid_amount !== null && (
                    <p>
                      <span className="font-semibold">Highest bid:</span>{" "}
                      {trackListData?.data?.listing?.currency === "USD"
                        ? "US$"
                        : "C$"}{" "}
                      {trackListData?.data?.listing?.top_bid_amount ?? 0}
                    </p>
                  )}
                  <p>
                    <span className="font-semibold">Total bids:</span>{" "}
                    {trackListData.data.listing.bid_count ??
                      trackListData.data.listing.bids?.length ??
                      0}
                  </p>
                </div>
              ) : (
                <p className="text-gray-500">No bid data available.</p>
              )}
            </div>
            {/* Order tracking (trackListData) */}
            <div className="container mx-auto p-4 bg-white rounded-md mt-4 xs:max-w-full">
              <h2 className="text-2xl text-black font-bold mb-3 text-start">
                Order Details
              </h2>
              {trackLoading ? (
                <div className="flex justify-center items-center">
                  <div className="loader2"></div>
                </div>
              ) : trackListData?.data?.listing ? (
                trackListData?.data?.listing?.order ? (
                  <div className="text-start text-gray-800 space-y-1">
                    <p>
                      <span className="font-semibold">Order ID:</span>{" "}
                      {trackListData.data.listing.order.id}
                    </p>
                    <p className="flex">
                      <span className="font-semibold capitalize">Product:</span>{" "}
                      <p className="capitalize">
                        {" "}
                        {trackListData.data.listing.product_name}
                      </p>
                    </p>
                    <p>
                      <span className="font-semibold">Amount:</span>
                      {trackListData?.data?.listing?.order?.currency === "USD"
                        ? "US$"
                        : "C$"}{" "}
                      {trackListData?.data?.listing?.order?.amount ?? 0}
                    </p>

                    <p>
                      <span className="font-semibold">Created at:</span>{" "}
                      {formatDate(trackListData.data.listing.order.created_at)}
                    </p>
                  </div>
                ) : (
                  <div className="pt-2">
                    <p>
                      This listing hasn’t received any order. Click the button
                      below to repost it."{" "}
                    </p>
                    {trackListData?.data?.listing?.can_repost === true && (
                      <button
                        onClick={() =>
                          router.push(
                            `/repostDetail?id=${trackListData.data.listing.id}`
                          )
                        }
                        className="bg-[#F8CB1F] hover:bg-[#F8CB1F] text-black font-semibold text-sm px-4 py-2 rounded mt-3"
                      >
                        Repost
                      </button>
                    )}
                  </div>
                )
              ) : (
                <p className="text-gray-500">No tracking data found.</p>
              )}
            </div>
            <div></div>
            {trackListData?.data?.listing?.order && (
              <div className="bg-white rounded-md p-4 xs:w-full mt-3">
                <div className="flex justify-center gap-4">
                  <div className="flex items-center justify-center w-24 h-24 lg:h-[144px] lg:w-[144px] rounded-full">
                    {trackListData?.data?.listing?.order?.buyer?.profile_url ? (
                      <Image
                        unoptimized
                        src={trackListData.data.listing.order.buyer.profile_url}
                        alt="user profile"
                        width={144}
                        height={144}
                        className="w-24 h-24 lg:h-[144px] lg:w-[144px] rounded-full object-cover"
                      />
                    ) : (
                      <div className="w-24 h-24 lg:h-[144px] lg:w-[144px] rounded-full bg-gray-200 flex items-center justify-center text-gray-500 text-sm">
                        N/A
                      </div>
                    )}
                  </div>
                </div>

                <div className="text-center mt-4 flex flex-col">
                  <h2 className="md:text-3xl xs:text-xl font-bold text-[#3D3D3D] capitalize">
                    {trackListData.data.listing.order.buyer?.name}
                  </h2>
                  <p className="md:text-lg xs:text-sm flex items-center gap-3 text-[#878787] justify-center pt-1 font-bold">
                    {trackListData.data.listing.order.buyer?.location}
                    <Image
                      unoptimized
                      src={profileLocation}
                      alt="Location icon"
                      width={18}
                      height={18}
                    />
                  </p>
                </div>
              </div>
            )}

            {/* Address card */}
            {trackListData?.data?.listing?.order && (
              <div className="container mx-auto p-4 bg-white rounded-md mt-4 xs:max-w-full">
                <h2 className="text-2xl text-black font-bold mb-3 text-start">
                  Address
                </h2>
                {trackLoading ? (
                  <div className="flex justify-center items-center">
                    <div className="loader2"></div>
                  </div>
                ) : trackListData?.data?.listing?.order?.address ? (
                  <div className="text-start text-gray-800 grid gap-1">
                    <p className="font-semibold text-gray-900">
                      {trackListData.data.listing.order.address.fullname}
                    </p>
                    <p>
                      {trackListData.data.listing.order.address.house_number}
                    </p>
                    <p>
                      {trackListData.data.listing.order.address.city}
                      {trackListData.data.listing.order.address.province
                        ? `, ${trackListData.data.listing.order.address.province}`
                        : ""}
                    </p>
                    <p>
                      {trackListData.data.listing.order.address.country}
                      {trackListData.data.listing.order.address.postal_code
                        ? `, ${trackListData.data.listing.order.address.postal_code}`
                        : ""}
                    </p>
                  </div>
                ) : null}
              </div>
            )}
          </div>

          <div className="xl:col-span-8 lg:col-span-8 xs:col-span-12 xs:p-0 p-4 ">
            <div className=" lg:p-0 xs:p-4 ">
              <div className="bg-white rounded-lg md:p-7 xs:p-3 ">
                <div className="grid md:grid-cols-2 xs:grid-cols-1">
                  <div>
                    <h1 className="md:text-3xl xs:text-[1.5rem] font-semibold text-gray-900 mb-4 text-start capitalize ">
                      {viewListingData?.product_name}
                    </h1>
                    <div>
                      <p className="text-[#A2A2A1] text-start font-bold text-lg">
                        Posted {formatDate(viewListingData?.created_at)}
                      </p>
                    </div>
                  </div>
                  {/*  */}
                </div>
                <div className="grid md:grid-cols-2 xs:grid-col-1">
                  {viewListingData?.product_type === "Reserved" &&
                    viewListingData.view_price_status && (
                      <div className="mb-2 text-lg font-bold text-green-500 flex gap-2">
                        <span className="font-bold text-gray-700">
                          Reserve Price:
                        </span>
                        <div className="flex flex-col">
                          <span>
                            {viewListingData?.currency === "USD" ? "US$" : "C$"}{" "}
                            {viewListingData?.reserve_price}
                          </span>
                          {currency != viewListingData?.currency && (
                            <span className="text-gray-500 font-semibold text-base text-left">
                              {viewListingData?.currency === "USD"
                                ? "C$"
                                : "US$"}{" "}
                              {convertCurrency(
                                parseFloat(
                                  Number(
                                    viewListingData?.reserve_price
                                  ).toFixed(3)
                                ),
                                viewListingData?.currency,
                                viewListingData?.currency === "USD"
                                  ? "CAD"
                                  : "USD",
                                rates
                              ).toFixed(2)}
                            </span>
                          )}
                        </div>
                      </div>
                    )}
                </div>
                {viewListingData?.sub_location && (
                  <div className="grid">
                    <div className="mb-2 text-lg font-bold text-black flex gap-2 capitalize">
                      <span className="font-bold text-gray-700 capitalize">
                        Location:
                      </span>
                      {viewListingData?.full_address &&
                        viewListingData?.full_address + ", "}
                      {viewListingData?.sub_location}
                    </div>
                  </div>
                )}
                {/* Removed unused isLoading overlay */}

                <div className="grid md:grid-cols-2 xs:grid-cols-1 justify-between mt-5"></div>
                {/* Helmet for SEO & Social Media Meta Tags */}

                <div className="flex  gap-4 lg:flex-row  xs:flex-col relative">
                  <div className="social-icons lg:flex-col md:justify-start gap-5 xs:flex xs:justify-between xs:items-center xs:m-0">
                    <ClientShareButtons
                      url={productUrl}
                      title={metaTitle}
                      description={metaDescription}
                      isProductLiked={false}
                      onToggleLike={() => {}}
                    />
                  </div>
                  {viewListingData ? (
                    <div className="flex gap-6 lg:flex-row xs:flex-col">
                      <div className="flex items-center relative overflow-hidden">
                        {isComingSoon && (
                          <div className="absolute top-[2rem] left-[-2.1rem] w-[184px] transform -rotate-[39deg] bg-[#F8CB1F] text-black text-center text-[17px] tracking-[0.010em] font-bold pt-[0.10rem] pb-[0.15rem] z-10">
                            Coming Soon
                          </div>
                        )}
                        {selectedImage ? (
                          <Image
                            unoptimized
                            src={selectedImage}
                            alt="Selected"
                            width={556}
                            height={370}
                            className="lg:w-[556px] lg:max-h-[370px] h-full w-full md:max-w-full cursor-pointer object-cover rounded-[20px]"
                            onClick={() => handleImageClick(selectedImage)}
                          />
                        ) : null}
                      </div>
                      <div className="flex xs:flex-row lg:flex-col md:gap-5 xs:gap-3 overflow-auto md:max-h-[372px] scrollbar-none">
                        {viewListingData?.images?.length > 0 &&
                          viewListingData.images.map(
                            (image: any, index: number) => (
                              <Image
                                unoptimized
                                key={index}
                                src={image}
                                alt={viewListingData?.product_name || "Image"}
                                width={150}
                                height={100}
                                className="md:max-w-[150px] md:max-h-[100px] xs:max-w-[170px] xs:h-[100px] mt-2 cursor-pointer md:rounded-[20px] xs:rounded-md object-cover"
                                onClick={() => handleImageClick(image)}
                              />
                            )
                          )}
                      </div>
                    </div>
                  ) : (
                    <div className="flex justify-center items-center">
                      <div className="loader2 absolute left-[50%] top-[50%]"></div>
                    </div>
                  )}

                  {/* Imported Image Modal */}
                  <ImageModal
                    isModalOpens={isModalOpens}
                    closeModal={closeModal}
                    selectedIndex={selectedIndex}
                    viewListingData={viewListingData}
                    handleImageClick={handleImageClick}
                  />
                </div>
              </div>

              <div className="container mx-auto p-4 bg-white rounded-md mt-4 xs:max-w-full">
                <h1 className=" text-start text-3xl font-bold mb-4 text-black capitalize">
                  Overview
                </h1>

                <hr className="mt-6"></hr>

                <div className="grid lg:grid-cols-2 xs:gird-col-12 gap-4 mt-5">
                  <div className="text-start">
                    {viewListingData?.shipping_details &&
                      viewListingData?.shipping_details != "null" && (
                        <div className="mb-2 font-medium  text-black flex gap-2 capitalize ">
                          <span className="font-medium  text-gray-700 ">
                            Shipping details:
                          </span>{" "}
                          {viewListingData?.shipping_details}
                        </div>
                      )}
                    <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                      <span className="font-medium  text-gray-700">
                        Product Name:
                      </span>{" "}
                      {viewListingData?.product_name}
                    </div>
                    <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                      <span className="font-medium  text-gray-700">
                        Sale by:
                      </span>{" "}
                      {viewListingData?.sale_by}
                    </div>
                    {viewListingData?.tax && (
                      <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                        <span className="font-medium  text-gray-700">Tax:</span>{" "}
                        {viewListingData?.tax}
                      </div>
                    )}

                    {viewListingData?.vin_number &&
                      viewListingData?.vin_number != "null" && (
                        <>
                          <div className="mb-2 font-medium  text-black flex gap-2">
                            <span className="font-medium  text-gray-700">
                              VIN Number:
                            </span>{" "}
                            {viewListingData?.vin_number}
                          </div>
                          <div>
                            <button
                              onClick={handleCarfax}
                              disabled={
                                viewListingData?.expired === 1 || auctionEnded
                              }
                              className={`
                                        bg-[#F8CB1F] py-2 px-6 rounded-md relative flex h-[35px]
                                        text-[1rem] items-center justify-center overflow-hidden font-semibold
                                        text-black shadow-sm border border-gray-200 
                                        hover:bg-white hover:text-black hover:border-gray-300
                                        ${
                                          viewListingData?.expired == 1 ||
                                          auctionEnded
                                            ? "pointer-events-none opacity-50"
                                            : ""
                                        }
                                      `}
                            >
                              CHECK CARFAX REPORT
                            </button>

                            <p className="text-sm text-gray-400 pt-1">
                              VIN will be copied to clipboard when you click the
                              button.
                            </p>
                          </div>
                        </>
                      )}
                  </div>
                  <div className="text-start">
                    {viewListingData?.website_link && (
                      <div className="mb-2 font-medium text-black flex gap-2 items-center">
                        <span className="font-medium text-gray-700">
                          Website Link:
                        </span>
                        <a
                          href={viewListingData.website_link}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600  hover:text-blue-800 break-all"
                        >
                          {viewListingData.website_link}
                        </a>
                      </div>
                    )}
                    {viewListingData?.youtube_link && (
                      <div className="mb-2 font-medium text-black flex gap-2 items-center">
                        <span className="font-medium text-gray-700">
                          YouTube:
                        </span>
                        <a
                          href={viewListingData.youtube_link}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-2 bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700 transition text-sm"
                        >
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 24 24"
                            fill="currentColor"
                            className="w-5 h-5"
                          >
                            <path d="M19.615 3.184C21.034 3.603 21.5 5.08 21.5 7.583v8.834c0 2.504-.466 3.98-1.885 4.399C17.905 21.2 12 21.2 12 21.2s-5.905 0-7.615-.384C2.966 20.397 2.5 18.92 2.5 16.417V7.583c0-2.504.466-3.98 1.885-4.399C6.095 2.8 12 2.8 12 2.8s5.905 0 7.615.384ZM10 9.5v5l5-2.5-5-2.5Z" />
                          </svg>
                          Open Video
                        </a>
                      </div>
                    )}

                    {viewListingData?.fuel_type &&
                      viewListingData?.fuel_type != "null" && (
                        <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                          <span className="font-medium  text-gray-700">
                            Fuel Type:
                          </span>{" "}
                          {viewListingData?.fuel_type}
                        </div>
                      )}
                  </div>
                </div>
                <hr className="mt-8"></hr>
                <h2 className="text-3xl text-black font-bold mb-3 text-start mt-5 ">
                  Description
                </h2>
                <p className="text-lg text-gray-600 font-medium  capitalize text-justify whitespace-pre-wrap">
                  {viewListingData?.description}
                </p>
              </div>
            </div>
          </div>
        </div>
        \{" "}
      </div>
    </>
  );
};

export default AuctionInfo;
