"use client";

import { AgentGrid } from "@/components/agent-grid";
import { Header } from "@/components/header";
import { motion, useScroll, useTransform } from "framer-motion";

import dynamic from "next/dynamic";
import { ConnectButton } from "@rainbow-me/rainbowkit";
import { Agent } from "@/types/agent";
import { useEffect, useState } from "react";
import { fetchAgentStats } from "@/lib/agents";

// 👇 Dynamically import the provider to avoid server-side import trace
const ClientQueryProvider = dynamic(() => import("./ClientQueryProvider").then(mod => mod.QueryProvider), {
  ssr: false,
});

function HomeContent() {
  const { scrollY } = useScroll();
  const backgroundColor = useTransform(scrollY, [0, 300], ["rgb(26, 26, 46)", "rgb(255, 255, 255)"]);

  const [agents, setAgents] = useState<Agent[] | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const updateAgent = (updatedAgent: Agent) => {
    setAgents(prevAgents =>
      prevAgents
        ? prevAgents.map(agent =>
          agent.agentId === updatedAgent.agentId ? updatedAgent : agent
        )
        : null
    );
  };

  useEffect(() => {
    let isMounted = true;

    const loadAgents = async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await fetch("/api/agents");
        if (!res.ok) throw new Error("Failed to fetch agents. ");
        const data = await res.json();
        const agents = await fetchAgentStats(data);
        if (isMounted) {
          setAgents(Array.isArray(agents) ? agents : [agents]);
        }
      } catch (err: any) {
        if (isMounted) {
          setError(err.message || "Error loading agents.");
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    loadAgents();

    return () => {
      isMounted = false;
    };
  }, []);

  return (
    <motion.main className="min-h-screen" style={{ backgroundColor }}>
      <div className="absolute top-4 right-4 z-30">
        <ConnectButton />
      </div>
      <Header />
      <div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
        {error ? (
          <div className="p-4 text-red-500">Error loading agents: {error}</div>
        ) : loading ? (
          <div className="flex justify-center items-center p-8">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
          </div>
        ) : (
          <AgentGrid agents={agents!} onUpdateAgent={updateAgent}/>
        )}
      </div>
    </motion.main>
  );
}

export default function Page() {
  return (
    <ClientQueryProvider>
      <HomeContent />
    </ClientQueryProvider>
  );
}
