"use client";

import { useEffect, useRef } from "react";
import { useAccount, useBalance } from "wagmi";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import { gsap } from "gsap";
import { formatBalance } from "@/lib/utils";

export function BalanceDisplay() {
  const { address } = useAccount();
  const { data: balance, isLoading } = useBalance({ address });
  const displayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (displayRef.current && balance) {
      gsap.from(displayRef.current, {
        opacity: 0,
        y: 20,
        duration: 0.8,
        ease: "power3.out",
      });
    }
  }, [balance]);

  if (isLoading) {
    return (
      <div className="bg-gray-900 rounded-xl p-8 h-64 flex items-center justify-center">
        <div className="text-gray-400">Loading balance...</div>
      </div>
    );
  }

  const balanceValue = balance?.value || BigInt(0);
  const formattedBalance = formatBalance(balanceValue);

  return (
    <div ref={displayRef} className="relative bg-gray-900 rounded-xl p-8 overflow-hidden border border-gray-800">
      <div className="absolute inset-0 bg-gradient-to-br from-blue-500/10 to-purple-500/10" />
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_50%,rgba(59,130,246,0.1),transparent_50%)]" />
      <div className="relative z-10">
        <h2 className="text-2xl font-semibold mb-4 bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
          Total Balance
        </h2>
        <div className="flex items-center gap-8">
          <div className="flex-1">
            <div className="text-5xl font-bold mb-2 bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
              {formattedBalance}
            </div>
            <div className="text-gray-400">{balance?.symbol || "ETH"}</div>
          </div>
          <div className="w-64 h-64">
            <Canvas camera={{ position: [0, 0, 5] }}>
              <ambientLight intensity={0.5} />
              <pointLight position={[10, 10, 10]} intensity={1.5} />
              <pointLight position={[-10, -10, -10]} intensity={0.5} color="#8b5cf6" />
              <mesh>
                <torusGeometry args={[1, 0.3, 16, 100]} />
                <meshStandardMaterial 
                  color="#3b82f6" 
                  metalness={0.8}
                  roughness={0.2}
                  emissive="#1e40af"
                  emissiveIntensity={0.2}
                />
              </mesh>
              <OrbitControls enableZoom={false} autoRotate autoRotateSpeed={2} />
            </Canvas>
          </div>
        </div>
      </div>
    </div>
  );
}

