"use client";

import { useEffect, useState } from "react";
import facebook from "../../../../assets/facebook.svg";
import whatsapp from "../../../../assets/whatsapp.svg";
import twitter from "../../../../assets/twitter___.svg";
import heart from "../../../../assets/heart.svg";
import mail from "../../../../assets/email.svg";
import { RootState } from "../../../../store";
import { useSelector } from "react-redux";
import cents from "../../../../assets/cent.png";
import Image from "next/image";

import CarInfoCard from ".././components/CarInfoCardProps";
function PreReview() {
  const { sellerProfile } = useSelector(
    (state: RootState) => state.SallerProfileReducer
  );

  const listingData = useSelector(
    (state: RootState) => state.viewListingReducer
  );
  const cardInfoData = sellerProfile?.data;
  const userID = listingData?.data?.data?.listing?.user_id;
  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const UnlockFee = incrementData?.data?.auctionFee[0]?.unlock_fee;
  interface SocialIcon {
    name: string;
    imageSrc: string;
  }

  const socialIcons: SocialIcon[] = [
    {
      name: "facebook",
      imageSrc: facebook, // Replace with actual import or URL
    },
    {
      name: "twitter",
      imageSrc: twitter,
    },
    {
      name: "whatsapp",
      imageSrc: whatsapp,
    },
    {
      name: "mail",
      imageSrc: mail,
    },
  ];

  const [viewListingData, setViewListingData] = useState<any>(null);
  const [selectedImage, setSelectedImage] = useState<any>(null);

  function convertHoursToTimeFormat(hours: number): string {
    if (typeof hours !== "number" || isNaN(hours) || hours < 0) {
      return "00h : 00m : 00s";
    }

    const formatTime = (unit: number) => (unit < 10 ? `0${unit}` : unit);

    return `${formatTime(hours)}h : 00m : 00s`;
  }

  useEffect(() => {
    if (viewListingData?.images?.length > 0) {
      setSelectedImage(viewListingData?.images[0]); // Set the first image by default
    }
  }, [viewListingData]); // Runs
  useEffect(() => {
    const storedData = localStorage.getItem("previewData");
    if (storedData) {
      setViewListingData(JSON.parse(storedData));
    }
  }, []);

  if (!viewListingData) return null;

  return (
    <>
      <div className="max-w-10xl m-auto h-[80vh] overflow-auto">
        <div className="text-gray-600 md:pt-8 md:gap-2 xs:pt-4 lg:flex xl:flex xs:flex ">
          <div className="text-gray-600 md:text-[1rem] xs:text-sm font-normal hover:text-yellow-500">
            Home <span> {">"} </span>
          </div>
          <p
            // {viewListingData?.category?.id, viewListingData?.category?.name }
            className="text-gray-600 md:text-[1rem] xs:text-sm font-normal hover:text-yellow-500 cursor-pointer flex"
          >
            {viewListingData?.categoryName} {">"}
          </p>

          <p className="md:text-[1rem] xs:text-sm font-normal capitalize text-[#F8CB1F] ">
            {""} {viewListingData?.product_name}
          </p>
        </div>

        <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-0 flex flex-col">
            <div className="bg-white  xs:w-full xs:p-0 flex flex-col items-start pt-10 pb-10 sm:p-7 rounded-md">
              <div className="text-start w-full ">
                <div className="flex justify-between ">
                  <p className="text-black text-lg">Total Bids :</p>
                  <span className="text-lg font-bold text-black">
                    {viewListingData?.bid_count || "0"}
                  </span>
                </div>
                <div className="flex justify-between">
                  <p className="text-black text-lg">Current price :</p>
                  <span className="text-[1.4rem] font-bold text-black">
                    {viewListingData?.currency === "CAD"
                      ? "C$"
                      : viewListingData?.currency === "USD"
                      ? "US$"
                      : ""}{" "}
                    {new Intl.NumberFormat("en-US", {
                      minimumFractionDigits: 2,
                      useGrouping: true,
                    })
                      .format(viewListingData?.starting_bid || 0)
                      .replace(/,/g, " ")}
                  </span>
                </div>
                <div className="bg-[#f4f4f4] mt-1">
                  <div className="flex justify-between border-b border-gray-200">
                    <p className="text-black text-base">Time Left :</p>
                    {viewListingData?.auction_ends_at && (
                      <div className="text-red-500 xs:justify-start md:text-lg font-medium md:justify-end flex items-end space-x-1">
                        {convertHoursToTimeFormat(
                          viewListingData?.auction_ends_at
                        )}
                      </div>
                    )}
                  </div>
                  <div className="flex justify-between border-b border-gray-200">
                    <p className="text-black  text-base">Item Status :</p>
                    <span className="text-lg text-black font-medium text-start">
                      {viewListingData?.product_type}
                    </span>
                  </div>
                  {viewListingData?.product_type === "Reserved" && (
                    <div className="flex text-black justify-between">
                      <p className="text-black  text-base">
                        Unlock Price Fee :
                      </p>
                      <span className="text-lg font-medium">
                        {viewListingData?.product_type === "Reserved"
                          ? `${UnlockFee} Cents`
                          : "00"}{" "}
                      </span>
                    </div>
                  )}
                </div>
              </div>

              <form className="w-full">
                <div className="flex flex-col mb-4">
                  <label
                    htmlFor="amount"
                    className="mb-2 text-xl text-black font-bold text-start mt-3"
                  >
                    Add Bid:
                  </label>
                  <input
                    type="text"
                    id="amount"
                    required
                    disabled
                    className="p-2 border rounded-sm focus:outline-none focus:ring-0 active:outline-none active:ring-0 "
                    placeholder="Enter price"
                  />
                  <button
                    className="mt-4 text-2xl font-bold p-3 bg-[#F8CB1F] text-black rounded-md hover:bg-[#E4B71C] focus:outline-none focus:ring-0 active:outline-none active:ring-0 w-full xs-full cursor-not-allowed opacity-60"
                    type="button"
                    disabled={status === "loading"}
                  >
                    {status === "loading" ? "Sending Bid..." : "Send Bid"}
                  </button>
                </div>
              </form>
              {/* Custom Modal for Bid Confirmation */}
            </div>
            <div>
              <div>
                <CarInfoCard
                  avatarUrl={cardInfoData?.profile_url || ""}
                  name={cardInfoData?.name || "N/A"}
                  location={cardInfoData?.location || ""}
                  user_id={userID}
                  view_profile="View Profile"
                  avgDay={cardInfoData?.average_replies_per_day || 0}
                  avgReplies="Avg. Replies"
                  days={cardInfoData?.seller_joined_days || 0}
                  daysOnReserveIt="Days On Reservitt"
                  replyPercentage={cardInfoData?.reply_rate || 0}
                  replyRate="Reply Rate"
                  showProfile={false}
                />
              </div>

              <div className="xs:max-w-full  pt-7">
                <div className="bg-white shadow rounded-lg p-6">
                  <>
                    <div className="mb-4">
                      <label className="block text-xl font-bold text-start mb-2 text-black">
                        Drop a message
                      </label>
                      <textarea
                        id="message"
                        placeholder="Enter your message here"
                        disabled
                        className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline resize-none"
                      ></textarea>
                    </div>

                    <div className="text-start mb-4">
                      <input
                        type="checkbox"
                        id="copy-email"
                        className="mr-2"
                        disabled
                      />
                      <label className="text-black text-base font-bold ">
                        Send me a copy of email
                      </label>
                    </div>
                  </>

                  <div>
                    <button
                      type="button"
                      className="w-full text-2xl bg-yellow-300 text-black font-medium py-2 px-4 rounded cursor-not-allowed opacity-60"
                    >
                      Send
                    </button>
                  </div>
                  <div></div>
                </div>
              </div>
            </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-0">
              <div className="bg-white rounded-lg md:p-7 xs:p-0">
                <div className="grid md:grid-cols-2 xs:grid-cols-1">
                  <div>
                    <h1 className="md:text-2xl xs:text-lg 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 {viewListingData?.auction_ends_at}
                      </p>
                    </div>
                  </div>
                  <div className="flex flex-col md:items-end mb-3 ">
                    {viewListingData?.product_type === "Reserved" ? (
                      <>
                        <span className="relative z-10 xs:text-xs cursor-not-allowed px-1 py-2 w-[163px] bg-customYellow text-black shadow-2xl rounded flex items-center justify-center font-semibold md:text-[0.900rem] xs:text-start opacity-50">
                          {viewListingData.view_price_status
                            ? "Generate Order"
                            : "UNLOCK RESERVE"}
                        </span>
                      </>
                    ) : null}

                    {viewListingData?.product_type === "Reserved" &&
                      !viewListingData.view_price_status && (
                        <p className="md:text-lg xs:text-sm text-gray-700 mt-1 text-start flex items-center gap-1">
                          <Image
                            unoptimized
                            src={cents}
                            alt="cents"
                            width={20} // equivalent to h-5 (5 * 4px)
                            height={20} // keeping it square for consistency
                            className="object-contain" // Optional: keeps image's aspect ratio
                          />{" "}
                          <span className="font-bold text-gray-900">
                            99 cents
                          </span>{" "}
                          to unlock reserve
                        </p>
                      )}
                  </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>
                        ${viewListingData?.reserve_price}
                      </div>
                    )}
                </div>

                <div className="grid md:grid-cols-2 xs:grid-cols-1 justify-between mt-5"></div>

                <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">
                    {socialIcons.map((icon) => (
                      <div key={icon.name} className="social-icon-container">
                        <div className="border  rounded-full max-w-max p-2 bg-[#E9E9E9] ">
                          <a
                            // href={icon}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            <Image
                              unoptimized
                              src={icon.imageSrc}
                              alt={icon.name}
                              width={32} // equivalent to max-w-8 (8 * 4px)
                              height={32} // equivalent to max-h-8 (8 * 4px)
                              className="object-contain"
                            />
                          </a>
                        </div>
                      </div>
                    ))}
                    <div className="border rounded-full max-w-max p-2 bg-[#E9E9E9] ">
                      <Image
                        unoptimized
                        src={heart}
                        alt="like button"
                        width={20} // equivalent to w-5 (5 * 4px)
                        height={20} // keeping it square for consistency
                        className="object-contain"
                      />{" "}
                    </div>
                  </div>

                  {/* Imported Image Modal */}
                  <div className="flex gap-6 lg:flex-row xs:flex-col">
                    {/* Main Image */}
                    <div className="flex items-center">
                      <Image
                        unoptimized
                        src={selectedImage}
                        alt="Selected"
                        width={500}
                        height={370}
                        className="lg:w-[500px] lg:max-h-[370px] h-full cursor-pointer object-cover rounded-[20px]"
                        // layout="intrinsic"
                      />
                    </div>

                    {/* Thumbnails */}
                    <div className="flex xs:flex-row lg:flex-col gap-5 overflow-auto md:max-h-[372px] scrollbar-none">
                      {viewListingData?.images?.map(
                        (image: any, index: any) => (
                          <Image
                            unoptimized
                            key={index}
                            src={image}
                            alt="Thumbnail"
                            width={140}
                            height={100}
                            className="md:min-w-[100px] md:min-h-[100px] xs:min-w-[70px] xs:h-[100px] mt-2 cursor-pointer md:rounded-[20px] xs:rounded-md object-cover"
                            onClick={() => setSelectedImage(image)}
                            // layout="intrinsic"
                          />
                        )
                      )}
                    </div>
                  </div>
                </div>
              </div>
              <div className="container mx-auto md: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">
                    <div className="mb-2 font-medium gap-2 text-black flex">
                      <span className="font-medium  text-gray-700 ">
                        Quantity:
                      </span>{" "}
                      {viewListingData?.quantity}
                    </div>
                    {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>
                    <div className="mb-2 font-medium  text-black flex gap-2  capitalize">
                      <span className="font-medium  text-gray-700">Tax:</span>{" "}
                      {viewListingData?.tax_type} {viewListingData?.tax_details}
                    </div>
                  </div>
                  <div className="text-start">
                    {viewListingData?.website_link && (
                      <div className="mb-2 font-medium  text-black flex gap-2 ">
                        <span className="font-medium  text-gray-700">
                          Website link:
                        </span>{" "}
                        {viewListingData?.website_link}
                      </div>
                    )}
                    {viewListingData?.youtube_link && (
                      <div className="mb-2 font-medium  text-black flex gap-2 ">
                        <span className="font-medium  text-gray-700">
                          Youtube link:
                        </span>{" "}
                        {viewListingData?.youtube_link}
                      </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>
                      )}
                    {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>
                </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 PreReview;
