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

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

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

  const hasFetched = useRef(false);

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

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

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

  useEffect(() => {
    if (hasFetched.current) return;
    hasFetched.current = true;
    fetchSlabHistory();
  }, [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) {
    return (
      <div className="mt-4 bg-[var(--color-naviBlue)] p-4 text-sm text-[var(--color-slate)]">
        No slab record found
      </div>
    );
  }

  return (
    <div className="mt-4 bg-[var(--color-naviBlue)] p-4">
      <div className="flex items-center gap-4">
        <img
          src={history.image}
          alt={history.card_title}
          className="h-20 w-20 rounded-lg object-cover"
        />

        <div className="flex-1">
          <h3 className="text-lg font-extrabold text-white">
            {history.card_title}
          </h3>

          <div className="mt-1 text-sm text-[var(--color-slate)]">
            Played on: {history.created_at}
          </div>

          <div className="mt-3 flex flex-wrap gap-3 text-sm">
            <span className="rounded-full bg-black/30 px-3 py-1 text-white">
              Game Price: ${history.game_price}
            </span>
            <span className="rounded-full bg-black/30 px-3 py-1 text-white">
              Card Price: ${history.card_price}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SlabHistory;
