import { useQuery } from "@tanstack/react-query";
import { useParams } from "react-router";
import { ErrorView } from "~/components/error/ErrorView";
import { LoadingView } from "~/components/loading/LoadingView";
import { fetchApi } from "~/lib/fetch";
import type { CryptocurrencyDetailsResponse } from "~/types/crypto-api";
import { DescriptionSection } from "./DescriptionSection";
import { useState } from "react";
import { KeyStats } from "./KeyStats";
import { PriceChart } from "./PriceChart";

export function CryptoDetailsPage() {
  const { id } = useParams();
  const [expandedView, setExpandedView] = useState(false);

  const { data, isPending, error } = useQuery({
    queryKey: ["cryptocurrencies", id],
    queryFn: () => fetchApi<CryptocurrencyDetailsResponse>(`https://api.next.code-camp.org/cryptocurrencies/${id}`)
  });

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

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

  return (
    <div>
      <DescriptionSection currency={data.currency} />

      <section className={expandedView ? "flex flex-col gap-4" : "grid gap-4 lg:grid-cols-5"}>
        <KeyStats currency={data.currency} />
        <PriceChart currency={data.currency} expanded={expandedView} onToggleExpand={() => setExpandedView(!expandedView)} />
      </section>
    </div>
  );
}
