import React, { useRef, useState } from "react";
import { createPortal } from "react-dom";

export type ParentTab = "all" | "upcoming" | "live";
export type ChildTab = "all" | string;

export type LeagueIcon = {
  id: string;
  name: string;
  icon: string;
};

export type GameTab = {
  id: string;
  icon: string;
  name: string;
  leagues?: LeagueIcon[]; // ✅ add leagues
};

type Props = {
  parentTab: ParentTab;
  setParentTab: (tab: ParentTab) => void;

  childTab: ChildTab;
  setChildTab: (tab: any) => void;
  setLeague: any;
  gameTabs: GameTab[];
};

export default function MatchTabs({
  parentTab,
  setParentTab,
  childTab,
  setChildTab,
  setLeague,
  gameTabs,
}: Props) {
  const [hoveredSport, setHoveredSport] = useState<string | null>(null);
  const [leagueDrop, setLeagueDrop] = useState<{
    show: boolean;
    x: number;
    y: number;
    leagues: LeagueIcon[];
    sportId: string;
  } | null>(null);

  const closeTimer = useRef<number | null>(null);
  const [mhover, setMhover] = useState("all");

  const handleParent = (tab: ParentTab) => {
    setParentTab(tab);
    // setChildTab("all");
  };

  const [tip, setTip] = useState<{
    text: string;
    x: number;
    y: number;
    show: boolean;
  }>({
    text: "",
    x: 0,
    y: 0,
    show: false,
  });

  const openDropdown = (tab: GameTab, el: HTMLElement) => {
    if (closeTimer.current) {
      window.clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }

    const r = el.getBoundingClientRect();
    const dropW = 256;
    const padding = 10;
    const centerX = r.left + r.width / 2;
    const clampedX = Math.max(
      padding + dropW / 2,
      Math.min(window.innerWidth - padding - dropW / 2, centerX),
    );

    setHoveredSport(tab.id);
    setLeagueDrop({
      show: true,
      x: clampedX,
      y: r.bottom + 8,
      leagues: tab.leagues || [],
      sportId: tab.id,
    });
  };

  const scheduleClose = (sportId: string) => {
    if (closeTimer.current) window.clearTimeout(closeTimer.current);

    closeTimer.current = window.setTimeout(() => {
      setHoveredSport((curr) => (curr === sportId ? null : curr));
      setLeagueDrop((curr) => (curr?.sportId === sportId ? null : curr));
      closeTimer.current = null;
    }, 250); // ✅ 250ms gives you time to move mouse
  };

  const cancelClose = () => {
    if (closeTimer.current) {
      window.clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
  };

  const showTip = (e: React.MouseEvent, text: string) => {
    const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
    setTip({
      text,
      x: r.left + r.width / 2,
      y: r.top - 30, // tooltip above
      show: true,
    });
  };

  const hideTip = () => setTip((p) => ({ ...p, show: false }));

  return (
    <div className="flex items-center flex-col lg:flex-row gap-3 justify-between">
      {/* PARENT TABS */}
      <div className="flex gap-2 md:gap-4 my-3 2xl:my-6">
        <button
          onClick={() => handleParent("all")}
          className={`px-3 md:px-4 cursor-pointer 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl transition-all ${
            parentTab === "all"
              ? "bg-(--color-blue) text-white"
              : "text-(--color-slate) hover:bg-gray-700"
          }`}
        >
          ALL
        </button>

        <button
          onClick={() => handleParent("upcoming")}
          className={`px-3 md:px-4 cursor-pointer 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl transition-all ${
            parentTab === "upcoming"
              ? "bg-(--color-blue) text-white"
              : "text-(--color-slate) hover:bg-(--color-gray)"
          }`}
        >
          UPCOMING
        </button>

        <button
          onClick={() => handleParent("live")}
          className={`px-3 md:px-4 cursor-pointer 2xl:px-6 py-1 md:py-2 2xl:py-3 font-extrabold text-xs md:text-sm font-sofia 2xl:text-2xl transition-all ${
            parentTab === "live"
              ? "bg-(--color-blue) text-white"
              : "text-(--color-slate) hover:bg-(--color-gray)"
          }`}
        >
          LIVE
        </button>
      </div>

      {/* CHILD TABS */}
      <div className="md:mt-3 2xl:mt-5 bg-[#151A24] px-4 flex items-center gap-2 md:gap-3 justify-between">
        {/* ALL ESPORTS */}
        <button
          onClick={() => {
            (setChildTab("all"), setMhover("all"));
            setParentTab("all");
          }}
          className={`font-sofia shrink-0 p-1 md:p-1.5 md:pb-2 font-extrabold mt-1 text-xs md:text-sm 2xl:text-xl tracking-tight ${
            childTab === "all"
              ? "opacity-100 border-b-2"
              : "border-b-2 border-transparent hover:opacity-100 opacity-80"
          }`}
        >
          ALL SPORTS
        </button>

        {/* ICON TABS */}
        <div className="overflow-visible">
          <div className="flex items-center gap-2 md:gap-3 scrollbar-hide">
            {gameTabs.map((tab) => (
              <div
                key={tab.id}
                className="relative shrink-0"
                onMouseEnter={(e) =>
                  openDropdown(tab, e.currentTarget as HTMLElement)
                }
                onMouseLeave={() => {
                  scheduleClose(tab.id);
                  setMhover(tab.id);
                }}
              >
                <button
                  onClick={() => {
                    setLeague(null);
                    setChildTab(tab.id);
                  }}
                  onMouseEnter={(e) => showTip(e, tab.name)}
                  onMouseLeave={hideTip}
                  className={`relative shrink-0 p-1 md:p-1.5 md:pb-2 sport-tb-cs ${
                    childTab === tab.id
                      ? "opacity-100 border-b-2 slt"
                      : "border-b-2 border-transparent hover:opacity-100 opacity-80"
                  }`}
                  aria-label={tab.name}
                  type="button"
                >
                  <img
                    src={tab.icon}
                    alt={tab.name}
                    className="w-5 h-5 cursor-pointer md:w-6 md:h-6 2xl:w-8 2xl:h-8"
                  />
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>

      {typeof document !== "undefined" &&
        tip.show &&
        createPortal(
          <div
            className="fixed z-[9999] -translate-x-1/2 rounded bg-black px-2 py-1 text-xs text-white pointer-events-none"
            style={{ left: tip.x, top: tip.y }}
          >
            {tip.text}
          </div>,
          document.body,
        )}

      {typeof document !== "undefined" &&
        leagueDrop?.show &&
        leagueDrop.leagues.length > 0 &&
        createPortal(
          <div
            className="fixed z-[99999] -translate-x-1/2"
            style={{ left: leagueDrop.x, top: leagueDrop.y }}
            onMouseEnter={cancelClose} // ✅ keep open
            onMouseLeave={() => scheduleClose(leagueDrop.sportId)} // ✅ close after leaving dropdown
          >
            <div className="bg-[#0B0F17] w-64 p-2 border border-[#29313D] rounded-lg shadow-lg">
              <div className="grid grid-cols-3 gap-2">
                {leagueDrop.leagues.map((lg) => (
                  <button
                    key={lg.id}
                    type="button"
                    onClick={() => {
                      setLeague(lg.id);
                      setChildTab(mhover);
                      setLeagueDrop(null);
                      setHoveredSport(null);
                      setParentTab("all");
                    }}
                    className="group relative flex items-center justify-center rounded-md hover:bg-white/5 p-1"
                  >
                    <img
                      src={lg.icon}
                      onError={(e) =>
                        (e.currentTarget.src = "/images/sports/img.svg")
                      }
                      alt={lg.name}
                      className="w-14 h-14 cursor-pointer rounded-md object-contain bg-[#111827] p-1"
                    />
                    <div className="pointer-events-none opacity-0 group-hover:opacity-100 transition absolute left-1/2 -translate-x-1/2 top-full z-[99999] mt-2 whitespace-nowrap text-xs bg-black text-white px-2 py-1 rounded">
                      {lg.name}
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>,
          document.body,
        )}
    </div>
  );
}
