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

const SpinHistory = () => {
  const user = useSelector((state: any) => state.auth.user) as User | null;

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

  const hasFetched = useRef(false);

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

    setLoading(true);
    setError("");
    try {
      const res = await getSpinHistory(user.userId, user.token); // ✅ change this

      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);
    }
  };

  useEffect(() => {
    if (!user?.userId || !user?.token) return;
    if (hasFetched.current) return;

    hasFetched.current = true;
    fetchSpinHistory();
  }, [user?.userId, user?.token]);

  if (loading) {
    return (
      <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>
    );
  }

  if (error) {
    return (
      <div className="mt-4 bg-red-500/10 p-4 text-sm text-red-400">
        {error}
      </div>
    );
  }

  if (!history.length) {
    return (
      <div className="mt-4 bg-[var(--color-naviBlue)] p-4 text-sm text-[var(--color-slate)]">
        No spin record found
      </div>
    );
  }

  return <div className="mt-4">Spin history loaded ({history.length})</div>;
};

export default SpinHistory;
