import { ErrorView } from "~/components/error/ErrorView";
import { PricingTable } from "./PricingTable";
import { useQuery } from "@tanstack/react-query";
import { LoadingView } from "~/components/loading/LoadingView";
import { fetchApi } from "~/lib/fetch";
import type { CryptocurrenciesListResponse } from "~/types/crypto-api";
import { TopCards } from "./TopCards";

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

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

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

  return (
    <div>
      <TopCards currencies={data.currencies} />
      <PricingTable currencies={data.currencies} />
    </div>
  );
}
