import { getFlipHistory } from "@/app/lib/api/coinFlip";
import { User } from "@/constants/types";
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";

type Player = {
  name: string;
  image: string;
  cards: string[];
  price: number;
};

type FlipItem = {
  id: number;
  player1: Player;
  player2: Player | [];
  winner: string;
  status: string;
  created_at: string;
};

type FlipHistoryResponse = {
  resp: string;
  data: FlipItem[];
};

export default function CoinFlipHistory() {
  const user = useSelector((state: any) => state.auth.user) as User | null;

  const [history, setHistory] = useState<FlipItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const hasFetched = useRef(false);
  const pageSize = 3;

  const [page, setPage] = useState(1);

  const totalPages = Math.ceil(history.length / pageSize) || 1;

  const paginatedData = history.slice((page - 1) * pageSize, page * pageSize);

  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };

  const fetchFlipHistory = async () => {
    if (!user?.userId || !user?.token) return;

    setLoading(true);
    setError("");
    try {
      const res = (await getFlipHistory(
        user.userId,
        user.token,
      )) as FlipHistoryResponse;

      if (res?.resp === "success" && Array.isArray(res.data)) {
        setHistory(res.data);
      } else {
        setError("Failed to load history");
      }
    } catch (e: any) {
      setError(e?.message || "Something went wrong");
      console.log(e);
    } finally {
      setLoading(false);
    }
  };

  // ✅ prevents double call in React 18 StrictMode (dev)
  useEffect(() => {
    if (!user?.userId || !user?.token) return;
    if (hasFetched.current) return;
    hasFetched.current = true;

    fetchFlipHistory();
  }, [user?.userId, user?.token]);

  useEffect(() => {
    setPage(1);
  }, [history.length]);

  const PlayerView = ({ label, p }: { label: string; p: Player | [] }) => {
    const isEmpty = Array.isArray(p);

    if (isEmpty) {
      return (
        <div className=" bg-[var(--color-naviBlue)] p-4 border border-white/10">
          <div className="text-xs font-extrabold font-sofia uppercase text-[var(--color-slate)]">
            {label}
          </div>
          <div className="mt-2 text-sm text-[var(--color-slate)] opacity-80">
            Waiting for opponent…
          </div>
        </div>
      );
    }

    return (
      <div className=" bg-[var(--color-naviBlue)] p-4 border border-white/10">
        <div className="text-xs font-extrabold font-sofia uppercase text-[var(--color-slate)]">
          {label}
        </div>

        <div className="mt-3 flex items-start gap-3">
          {p.image ? (
            <img
              src={p.image}
              alt={p.name}
              className="h-10 w-10 rounded-full object-cover border border-white/10"
            />
          ) : (
            <div className="h-10 w-10 rounded-full bg-white/10" />
          )}

          <div className="min-w-0 flex-1">
            <div className="truncate text-sm font-extrabold font-sofia text-white">
              {p.name}
            </div>

            <div className="mt-0.5 text-xs text-[var(--color-slate)]">
              Price:{" "}
              <span className="font-bold text-white">
                ${Number(p.price).toFixed(2)}
              </span>{" "}
              <span className="mx-1 opacity-60">•</span>
              Cards:{" "}
              <span className="font-bold text-white">
                {p.cards?.length ?? 0}
              </span>
            </div>

            {p.cards?.length ? (
              <div className="mt-2 flex flex-wrap gap-2">
                {p.cards.map((c, idx) => (
                  <span
                    key={idx}
                    className="rounded-full bg-black/30 px-2 py-1 text-[11px] text-white/90 border border-white/10"
                    title={c}
                  >
                    {c.split("/").pop()}
                  </span>
                ))}
              </div>
            ) : null}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="w-full">
      <div className="flex items-center justify-between gap-3">
        <h1 className="text-base md:text-lg 2xl:text-xl font-extrabold font-sofia text-white uppercase">
          Coin Flip History
        </h1>

        <button
          onClick={() => {
            // allow manual refresh
            hasFetched.current = false;
            fetchFlipHistory();
          }}
          className="px-4 py-2 text-xs md:text-sm font-extrabold font-sofia uppercase bg-[var(--color-naviBlue)] border-b-4 border-transparent hover:bg-gray-700/50 text-[var(--color-slate)] hover:text-white"
        >
          Refresh
        </button>
      </div>

      {loading ? (
        <div className="flex w-full h-[160px] items-center justify-center">
          <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
        </div>
      ) : null}

      {error ? (
        <div className="mt-4  bg-red-500/10 p-4 text-sm text-red-400 border border-red-500/20">
          {error}
        </div>
      ) : null}

      {!loading && !error && history.length === 0 ? (
        <div className="mt-4  bg-[var(--color-naviBlue)] p-4 text-sm text-[var(--color-slate)] border border-white/10">
          No history found.
        </div>
      ) : null}

      <div className="mt-4 grid gap-4">
        {paginatedData.map((g) => (
          <div
            key={g.id}
            className=" bg-[var(--color-naviBlue)] p-4 border border-white/10"
          >
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div className="text-sm md:text-base font-extrabold font-sofia text-white uppercase">
                Game #{g.id}
              </div>
              <div className="text-xs text-[var(--color-slate)] opacity-80">
                {g.created_at}
              </div>
            </div>

            <div className="mt-2 flex flex-wrap gap-2 text-xs">
              <span
                className={`rounded-full px-3 py-1 font-extrabold font-sofia uppercase border ${
                  g.status === "complete"
                    ? "bg-emerald-500/10 text-emerald-300 border-emerald-500/20"
                    : "bg-amber-500/10 text-amber-300 border-amber-500/20"
                }`}
              >
                {g.status}
              </span>

              <span className="rounded-full px-3 py-1 font-extrabold font-sofia uppercase bg-black/30 text-white/90 border border-white/10">
                Winner: {g.winner}
              </span>
            </div>

            <div className="mt-4 grid gap-3 md:grid-cols-2">
              <PlayerView label="Player 1" p={g.player1} />
              <PlayerView label="Player 2" p={g.player2} />
            </div>
          </div>
        ))}
      </div>
      {totalPages > 1 && (
        <div className="m-6 flex items-center justify-center gap-3 font-onest">
          <button
            onClick={() => goToPage(page - 1)}
            disabled={page === 1}
            className="flex h-[34px] w-[34px] items-center justify-center rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
          >
            <img src="/images/profile/left.svg" alt="prev" />
          </button>

          {/* Page numbers */}
          <div className="flex gap-2 text-sm">
            {[...Array(totalPages)].map((_, i) => {
              const pg = i + 1;

              // show only first, last, current, and neighbors
              if (pg === 1 || pg === totalPages || Math.abs(pg - page) <= 1) {
                return (
                  <button
                    key={pg}
                    onClick={() => goToPage(pg)}
                    className={`rounded px-3 py-1 ${
                      pg === page
                        ? "scale-115 text-white"
                        : "text-[var(--color-naturalGray)]"
                    }`}
                  >
                    {pg}
                  </button>
                );
              }

              // ellipsis
              if (pg === page - 2 || pg === page + 2) {
                return (
                  <span key={`ellipsis-${pg}`} className="px-2 text-gray-400">
                    ...
                  </span>
                );
              }

              return null;
            })}
          </div>

          <button
            onClick={() => goToPage(page + 1)}
            disabled={page === totalPages}
            className="flex h-[34px] w-[34px] items-center justify-center rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
          >
            <img src="/images/profile/right.svg" alt="next" />
          </button>
        </div>
      )}
    </div>
  );
}
