import { useQuery } from "@tanstack/react-query";
import { TokenCard } from "./TokenCard";
import { fetchApi } from "~/lib/fetch";
import type { Erc20TokensListResponse } from "~/types/api";
import { LoadingView } from "~/components/loading/LoadingView";
import { ErrorView } from "~/components/error/ErrorView";
import { useNavigate } from "react-router";
import { useConnection } from "wagmi";
import { useEffect } from "react";

export function HomePage() {
  const { data, isPending, error } = useQuery({
    queryKey: ['tokens'],
    queryFn: () => fetchApi<Erc20TokensListResponse>("https://api.next.code-camp.org/erc20-tokens")
  });

  const navigate = useNavigate();
  const { address, isConnected } = useConnection();

  useEffect(() => {
    if (!isConnected) {
      navigate('/status');
    }
  }, [isConnected, navigate]);


  if (isPending) {
    return <LoadingView />;
  }

  if (error) {
    return <ErrorView />;
  }

  if (!address || !isConnected) {
    return null;
  }

  return (
    <div className="flex flex-col gap-10">
      {data.tokens.map(token => (
        <TokenCard key={token.id} token={token} address={address} />
      ))}
    </div>
  );
}
