"use client";

import { useEffect, useState, ReactNode } from "react";
import { useDispatch, useSelector } from "react-redux";
import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { AppDispatch, RootState } from "../../store";
import { profileBuyer, ratingInfo } from "../../api/api";
import { HiOutlineInformationCircle } from "react-icons/hi";

interface Tab {
  name: string;
  href: string;
}

const tabs: Tab[] = [
  { name: "My Profile", href: "/profile/edits" },
  { name: "Purchased", href: "/profile/listing" },
  { name: "Listing", href: "/profile/seller/listing" },
  { name: "Sold Items", href: "/profile/orders" },
  { name: "Wishlist", href: "/profile/wishlist" },
  { name: "Security", href: "/profile/security" },
  { name: "Notification Settings", href: "/profile/notification" },
  { name: "Wallet", href: "/profile/wallet/transaction" },
  { name: "Chats", href: "/profile/chat" },
  { name: "Review", href: "/profile/review" },
  { name: "Tickets", href: "/profile/tickets" },
  { name: "Bid History", href: "/profile/bidHistory" },
];

export default function ProfileLayout({ children }: { children: ReactNode }) {
  const dispatch: AppDispatch = useDispatch();
  const pathname = usePathname();
  const router = useRouter();
  const { ticketsData } = useSelector(
    (state: RootState) => state.TicketsReducer
  );
  const [showInfo, setShowInfo] = useState(false);
  const [letter, setLetter] = useState("U");
  const [name, setName] = useState("");
  const [activeTab, setActiveTab] = useState<string>("");
  const [profileImage, setProfileImage] = useState<string | undefined>();

  const { buyerProfile, reatingData } = useSelector(
    (state: RootState) => state.profileReducer
  );

  // ✅ Prefetch all profile tab routes on mount
  useEffect(() => {
    tabs.forEach((tab) => router.prefetch(tab.href));
  }, [router]);

  useEffect(() => {
    dispatch(profileBuyer());
  }, [dispatch]);
  useEffect(() => {
    dispatch(ratingInfo());
  }, [dispatch]);

  useEffect(() => {
    if (buyerProfile?.data) {
      const userName = buyerProfile.data.name || "User";
      setName(userName);
      setLetter(userName.trim().charAt(0).toUpperCase() || "U");
      if (buyerProfile.data.profile_url) {
        setProfileImage(buyerProfile.data.profile_url);
      }
    }
  }, [buyerProfile]);

  useEffect(() => {
    const currentTab = tabs.find((tab) => pathname.startsWith(tab.href));
    if (pathname.includes("profile/edit-profile")) {
      setActiveTab("edit");
    } else if (currentTab) {
      setActiveTab(currentTab.name);
    } else {
      setActiveTab("");
    }
  }, [pathname]);

  return (
    <main className="flex lg:flex-row bg-[#F8F9F9] flex-col gap-8 font-system max-w-7xl mx-auto pt-12">
      {/* Sidebar */}
      <aside className="xs:px-2">
        <div className="bg-white relative shadow-lg rounded-xl flex flex-col items-center space-y-4 lg:w-[300px] mb-10">
          <div className="h-[89px] w-full bg-[#04104E] rounded-t-xl" />

          {profileImage ? (
            <div className="absolute top-[29px] w-20 h-20">
              <div className="relative w-20 h-20 rounded-full overflow-hidden">
                <Image
                  unoptimized
                  src={profileImage}
                  alt="Profile"
                  fill
                  className="object-cover"
                />
              </div>
            </div>
          ) : (
            <div className="absolute top-[29px] bg-white shadow-xl text-[#04104E] py-4 w-20 h-20 rounded-full text-center text-5xl font-semibold capitalize">
              {letter}
            </div>
          )}

          <div className="pt-10 text-center">
            <p className="text-2xl font-semibold text-gray-600 capitalize font-Family">
              {name}
            </p>
          </div>
          <div className="bg-white flex items-center justify-between gap-2">
            {/* Rating */}
            <p className="text-lg font-semibold text-gray-700 capitalize">
              Rating Points:{" "}
              <div className="relative inline-flex items-center justify-center">
                {/* Rating points */}
                <span className="text-blue-600 font-bold text-lg">
                  {buyerProfile?.data?.rating_points ?? 0}
                </span>

                {/* Info icon positioned like a badge with tooltip */}
                <div className="relative group">
                  <button
                    onClick={() => setShowInfo(true)}
                    className="absolute -top-9 -right-9"
                  >
                    <HiOutlineInformationCircle className="text-xl text-gray-500" />
                  </button>

                  {/* Tooltip */}
                  <div className="absolute -top-10 right-0 hidden group-hover:block bg-gray-800 text-white text-xs rounded-md px-2 py-1 shadow-lg whitespace-nowrap">
                    Info about rating points
                  </div>
                </div>
              </div>
            </p>
          </div>

          <nav className="pt-7 pb-16 w-[300px]">
            {tabs.map((tab) => {
              // only for Tickets tab
              const unreadTicketCount =
                tab.name === "Tickets"
                  ? ticketsData?.data?.totalUnread || 0
                  : 0;

              return (
                <Link
                  key={tab.name}
                  href={tab.href}
                  className={`block text-[20px] bg-[#F8F8F8] text-center p-2 font-medium w-full shadow-[0_-0px_1px_#00000040,0_0px_1px_#00000040] ${
                    activeTab === tab.name
                      ? "border-l-2 border-[#F8CB1F] text-yellow-500 font-bold hover:text-yellow-500"
                      : "text-[#454545] hover:text-[#454545]"
                  }`}
                  aria-current={activeTab === tab.name ? "page" : undefined}
                >
                  {tab.name}
                  {/* ✅ small badge just for Tickets */}
                  {tab.name === "Tickets" && unreadTicketCount > 0 && (
                    <span className="ml-2 text-sm font-bold text-red-500">
                      ({unreadTicketCount})
                    </span>
                  )}
                </Link>
              );
            })}
          </nav>
        </div>
      </aside>

      {/* Content */}
      <section className="right_section lg:min-w-[67%] md:p-3 lg:py-0 lg:px-2">
        {children}
      </section>

      {showInfo && (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
          <div className="bg-white rounded-xl shadow-lg p-6 max-w-md w-full mx-4 relative">
            {/* Close button */}
            <button
              onClick={() => setShowInfo(false)}
              className="absolute top-3 right-3 text-gray-400 hover:text-gray-600"
            >
              ✕
            </button>

            <h2 className="text-xl font-bold mb-4 text-gray-800">
              Rating Info
            </h2>

            <div
              className="text-gray-600 text-sm leading-relaxed"
              dangerouslySetInnerHTML={{
                __html:
                  reatingData?.data?.[0]?.description || "No details available",
              }}
            />

            <div className="mt-6 text-center">
              <button
                onClick={() => setShowInfo(false)}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}
