"use client";

import React, { useEffect, useState } from "react";
import CarInfoCard from "../../../components/bayerProfile/pages/components/CarInfoCardProps";
import { RootState } from "../../../store";
import { useSelector, useDispatch } from "react-redux";
import { viewSaller, sendMessage } from "../../../api/api";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { toast } from "react-toastify";
import { formatDate } from "../../../common/DateFormant";
import AuctionProduct from "../../../common/AuctionProduct";
import Review from "../../../components/bayerProfile/pages/components/Review";
import { truncateDescription } from "../../../utils/commonFunction";
import Image from "next/image";
import TimeAgo from "../../../common/TimeAgo";
import { DateTime } from "luxon";
const ITEMS_PER_PAGE = 3;
const ProfileViewSeller: React.FC = () => {
  const [activeTab, setActiveTab] = useState("listings");
  const [message, setMessage] = useState("");
  const [sendCopy, setSendCopy] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const { id } = useParams<{ id: string }>();
  const data = useSelector((state: RootState) => state.ViewSeller);
  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const CurrentUserID = userData?.data?.user?.id;
  const cardInfoData = data?.data?.data?.seller;
  const user = userData?.data?.user;
  const tabs = [
    { name: "Listings", key: "listings" },
    { name: "Reviews", key: "reviews" },
  ];

  const dispatch = useDispatch<any>();
  const router = useRouter();
  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const userTimeZone = homedata?.data?.settings.default_timezone || "UTC";

  useEffect(() => {
    if (id) {
      dispatch(viewSaller({ seller_id: id, user_id: CurrentUserID }));
    }
  }, [dispatch, id, CurrentUserID]);

  const handleSubmitMessage = async () => {
    if (!user?.id) {
      toast.error("User ID not found. Please log in.");
      return;
    }

    const payload = {
      to_user_id: user.id,
      message,
      sendCopy,
    };

    try {
      await dispatch(sendMessage(payload));
      toast.success("Message sent successfully!");
      setMessage("");
      router.push("/profile/chat");
    } catch {
      toast.error("Failed to send message. Please try again.");
      // console.error("Error sending message:", err);
    }
  };
  const getAuctionUrl = (
    id: number,
    categoryName?: string,
    productName?: string
  ) => {
    const formattedCategoryName = (
      categoryName?.replace(/[^a-zA-Z0-9\s]/g, "").replace(/\s+/g, "-") ||
      "default-category"
    ).toLowerCase();

    const formattedProductName = (
      productName?.replace(/[^a-zA-Z0-9\s]/g, "").replace(/\s+/g, "-") ||
      "default-product"
    ).toLowerCase();

    return `/auction/${id}/${formattedCategoryName}/${formattedProductName}`;
  };
  const auctionsListing = data?.data?.data?.listings?.data || [];
  const totalPages = Math.ceil(auctionsListing.length / ITEMS_PER_PAGE);

  const paginatedListings = auctionsListing.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );
  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage((prevPage) => prevPage + 1);
    }
  };

  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage((prevPage) => prevPage - 1);
    }
  };

  const handleRedirection = (
    id: number,
    categoryName?: string,
    productName?: string
  ) => {
    const url = getAuctionUrl(id, categoryName, productName);
    router.push(url);
  };

  function formatStartDateTime(datetimeStr: string): string {
    if (!datetimeStr) return "";

    const [datePart, timePartRaw] = datetimeStr.split(" ");

    const timePart = timePartRaw ?? "00:00:00";

    const fixDateFormat = (dateStr: string) => {
      if (dateStr.includes(" ") && !dateStr.includes("T")) {
        return dateStr.replace(" ", "T");
      }
      return dateStr;
    };

    const fullDateTimeStr = fixDateFormat(`${datePart} ${timePart}`);
    const dateObj = new Date(fullDateTimeStr);

    if (isNaN(dateObj.getTime())) {
      // console.error("Invalid date format in formatStartDateTime:", datetimeStr);
      return "";
    }

    const timeFormatted = dateObj.toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
    });

    return `${datePart} ${timeFormatted}`;
  }

  return (
    <div className="max-w-7xl mx-auto">
      <div className="flex text-gray-600 lg:pt-10 gap-2 xs:px-4">
        <Link
          href={`/`}
          className="text-gray-600 text-lg font-medium  hover:text-yellow-500"
        >
          Home <span> {">"} </span>
        </Link>
        <p className="text-gray-600 text-lg font-medium hover:text-yellow-500">
          Seller Profile{" "}
        </p>
      </div>

      <div className="grid grid-cols-12 lg:pt-11 gap-7">
        <div className="lg:col-span-4 xs:col-span-12 flex flex-col">
          <div className="lg:p-0 xs:p-4">
            <CarInfoCard
              avatarUrl={cardInfoData?.profile_url || ""}
              name={cardInfoData?.name || "N/A"}
              location={cardInfoData?.location}
              avgDay={cardInfoData?.average_replies_per_day || 0}
              view_profile="View Profile"
              user_id={id}
              avgReplies="Avg. Replies"
              days={cardInfoData?.days_on_reserveitt}
              daysOnReserveIt="Days On Reservitt"
              replyPercentage={cardInfoData?.reply_rate || 0}
              replyRate="Reply Rate"
            />

            <div className="bg-white shadow rounded-lg p-6 mt-3">
              <div className="flex flex-col text-start text-black cursor-pointer">
                {tabs.map((tab) => (
                  <div
                    key={tab.key}
                    onClick={() => {
                      setActiveTab(tab.key);
                    }}
                    className={`p-2 text-black ${
                      activeTab === tab.key
                        ? "font-bold border-l-2 border-[#F8CB1F]"
                        : ""
                    }`}
                  >
                    {tab.name}
                  </div>
                ))}
              </div>
            </div>

            <div className="mx-auto pt-3 mb-3 hidden lg:flex xl:flex">
              <div className="bg-white shadow rounded-lg p-6 w-full">
                <div className="mb-4">
                  <label className="block text-xl font-bold text-start mb-2 text-black">
                    Drop a message
                  </label>
                  <textarea
                    id="message"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    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"
                    checked={sendCopy}
                    onChange={(e) => setSendCopy(e.target.checked)}
                    className="mr-2"
                  />
                  <label className="text-gray-700 text-sm font-bold">
                    Send me a copy of email
                  </label>
                </div>

                <div>
                  <button
                    type="button"
                    onClick={handleSubmitMessage}
                    className="w-full bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                  >
                    Send
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="lg:col-span-8 xs:col-span-12 px-4">
          {activeTab === "listings" && (
            <div>
              {paginatedListings.map((listing: any, index: number) => {
                const currentTime = DateTime.fromFormat(
                  listing?.current_time_formatted,
                  "yyyy-MM-dd HH:mm:ss",
                  {
                    zone: userTimeZone,
                  }
                );

                // Convert auction start time
                const auctionStartTime = DateTime.fromISO(
                  listing?.start_datetime?.replace(" ", "T"),
                  { zone: userTimeZone }
                );
                // Check if auction is coming soon
                const isComingSoon = auctionStartTime > currentTime;

                return (
                  <div
                    key={index}
                    onClick={() =>
                      handleRedirection(
                        listing.id,
                        listing?.category?.name,
                        listing.product_name
                      )
                    }
                    onMouseEnter={() => {
                      const url = getAuctionUrl(
                        listing.id,
                        listing?.category?.name,
                        listing.product_name
                      );
                      router.prefetch(url);
                    }}
                    className="flex  w-full md:max-w-full md:flex lg:max-w-full lg:flex mb-4 mt-3 rounded-lg bg-white sm:m-auto sm:mb-4 lg:p-3 lg:gap-3 md:gap-5 cursor-pointer transition-transform duration-300 hover:scale-105 hover:shadow-lg xs:mx-auto xs:gap-2 xs:p-2"
                  >
                    {/* Image Container */}
                    <div className="relative">
                      {listing?.images?.[0] ? (
                        <Image
                          unoptimized
                          className="md:max-w-56 object-cover md:h-[228px] xs:h-[126px] xs:min-w-[125px] lg:p-0 md:rounded-2xl h-auto xs:rounded-xl"
                          src={listing.images[0]}
                          alt={listing.product_name}
                          width={300}
                          height={228}
                        />
                      ) : (
                        <div className="md:max-w-56 md:h-[228px] xs:h-[126px] xs:min-w-[125px] lg:p-0 md:rounded-2xl h-auto xs:rounded-xl bg-gray-200 flex items-center justify-center text-sm text-gray-500">
                          No Image
                        </div>
                      )}

                      {/* Coming Soon Overlay */}
                      {isComingSoon && (
                        <div className="absolute inset-0 bg-gradient-to-b from-black/60 to-transparent flex flex-col items-center justify-center text-center text-white md:p-4 bg-black opacity-70 md:rounded-2xl  xs:rounded-xl">
                          <span className="md:text-[1.25rem] xs:text-[0.800rem] md:leading-[2rem] font-bold uppercase animate-pulse tracking-widest">
                            Coming Soon
                          </span>
                          <p className="md:text-base xs:text-[0.700rem]  opacity-80">
                            Stay tuned! Items will be available soon.
                          </p>
                          <span className="md:text-base xs:text-[0.700rem]  opacity-80">
                            {formatStartDateTime(listing?.start_datetime)}
                          </span>
                        </div>
                      )}
                    </div>

                    {/* Product Info */}
                    <div className="bg-white rounded-b lg:rounded-b-none lg:rounded-r flex flex-col justify-between leading-normal w-full">
                      <div>
                        <div className="xs:text-xl text-gray-900 font-bold lg:pt-1 md:text-3xl text-start capitalize">
                          {listing.product_name}
                        </div>
                        <div className="xs:text-sm md:text-lg lg:text-lg lg:pt-3 text-[#A2A2A1]">
                          <p className="flex items-center gap-2">
                            <span>{formatDate(listing.created_at)}</span> |
                            <span>{listing?.location}</span>
                          </p>
                        </div>
                        <p className="hidden text-black-700 text-start lg:text-lg lg:pt-3 md:font-semibold md:block">
                          {truncateDescription(
                            listing.description || "No description available."
                          )}
                        </p>
                        <div className="flex md:justify-between mt-2 xs:gap-1 items-center">
                          {/* View Button */}
                          <div className="md:custom-button-price xs:custom-button-sm">
                            <span className="relative z-10 xs:text-xs font-semibold md:text-[0.900rem]">
                              VIEW
                            </span>
                          </div>
                          {/* Timestamp */}
                          <p className="font-bold xs:text-xs md:text-lg  text-gray-500">
                            <TimeAgo timestamp={listing.created_at} />
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
          {/* Reviews for listing  */}
          {activeTab === "reviews" && (
            <div>
              <Review />
            </div>
          )}

          {activeTab === "listings" && (
            <div className="flex justify-end lg:pt-6 lg:pr-0 pb-6 gap-6 xs:pt-2 xs:pr-5">
              <button
                onClick={handlePrevPage}
                disabled={currentPage === 1}
                className={`px-4 py-2 rounded text-white ${
                  currentPage === 1
                    ? "bg-gray-300 cursor-not-allowed"
                    : // : "bg-yellow-500 hover:bg-yellow-700 transition-transform duration-300 hover:scale-105"
                      "bg-yellow-500 hover:bg-yellow-700"
                }`}
              >
                Previous
              </button>

              <button
                onClick={handleNextPage}
                disabled={currentPage === totalPages}
                className={`px-4 py-2 rounded text-white ${
                  currentPage === totalPages
                    ? "bg-gray-300 cursor-not-allowed"
                    : // : "bg-yellow-500 hover:bg-yellow-700 transition-transform duration-300 hover:scale-105"
                      "bg-yellow-500 hover:bg-yellow-700"
                }`}
              >
                Next
              </button>
            </div>
          )}
        </div>
      </div>
      {/* Recommended  product */}
      <AuctionProduct />

      {/* For small screen */}
      <div className="pt-3 xs:flex lg:hidden p-4">
        <div className="bg-white shadow rounded-lg p-6 w-full">
          <div className="mb-4">
            <label className="block text-sm font-bold text-start mb-2 text-black">
              Drop a message
            </label>
            <textarea
              id="message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              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"
              checked={sendCopy}
              onChange={(e) => setSendCopy(e.target.checked)}
              className="mr-2"
            />
            <label className="text-gray-700 text-sm font-bold">
              Send me a copy of email
            </label>
          </div>

          <div>
            <button
              type="button"
              onClick={handleSubmitMessage}
              className="w-full bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
            >
              Send
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProfileViewSeller;
