import clsx from "clsx";
import type { CryptocurrenciesListResponse } from "~/types/crypto-api";
import { formatPercentage } from "~/utils/format";

function TopCard({ header, value, footer, percentChange }) {
  return (
    <article className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="flex items-start justify-between">
        <div>
          <p className="text-sm font-medium text-slate-600">{header}</p>
          <p className="text-3xl font-semibold mt-2">{value}</p>
        </div>

        {percentChange !== null && (
          <span
            className={clsx(
              "inline-flex items-center rounded-full px-3 py-1 text-xs font-medium",
              percentChange > 0
                ? "bg-emerald-100 text-emerald-700"
                : "bg-rose-100 text-rose-700"
            )}
          >
            {formatPercentage(percentChange)}
          </span>
        )}
      </div>
      <p className="mt-4 text-xs text-slate-500">{footer}</p>
    </article>
  );
}

export function TopCards({
  currencies
}: {
  currencies: CryptocurrenciesListResponse["currencies"];
}) {
  const bitcoin = currencies.find((c) => c.slug === "bitcoin")!;

  const gainersCount = currencies.filter((c) => c.percent_change_24h > 0).length;
  const losersCount = currencies.filter((c) => c.percent_change_24h < 0).length;

  const averagePriceChange = currencies.reduce((prev, current) => prev + current.percent_change_24h, 0) / currencies.length;

  const totalVolume = currencies.reduce((prev, current) => prev + current.volume_24h, 0);
  const averageVolume = totalVolume / currencies.length;

  return (
    <section className="grid gap-4 md:grid-cols-3">
      <TopCard
        header="Bitcoin (BTC)"
        value={`$${bitcoin.price.toLocaleString()}`}
        footer="Bitcoin is the top cryptocurrency."
        percentChange={bitcoin.percent_change_24h}
      />

      <TopCard
        header="Top 50 Average (24h)"
        value={formatPercentage(averagePriceChange)}
        footer={`Gainers: ${gainersCount} | Losers: ${losersCount}`}
        percentChange={averagePriceChange}
      />

      <TopCard
        header="Top 50 Total Volume (24h)"
        value={`$${(totalVolume / 1_000_000_000).toFixed(1)}B`}
        footer={`Avg. volume per coin: $${(averageVolume / 1_000_000_000).toFixed(1)}B`}
        percentChange={null}
      />
    </section>
  );
}
