import clsx from "clsx";
import { Area, AreaChart, XAxis, YAxis } from "recharts";
import type { CryptocurrencyDetailsResponse } from "~/types/crypto-api";
import { formatPercentage } from "~/utils/format";

export function PriceChart({
    currency,
    expanded,
    onToggleExpand
  }: {
    currency: CryptocurrencyDetailsResponse["currency"];
    expanded: boolean;
    onToggleExpand: () => void;
  }) {
    return (
        <div className="lg:col-span-3 rounded-2xl border border-slate-200 bg-white shadow-sm">
          <div className="flex flex-col gap-3 border-b border-slate-200 p-5 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <h2 className="text-base font-semibold text-slate-900">Price Chart</h2>
              <p className="mt-1 text-xs text-slate-500">Historical price movement of the cryptocurrency.</p>
            </div>

            <div className="flex-wrap gap-2 hidden md:flex">
              <button className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-100" type="button" onClick={onToggleExpand}>
                {expanded ? 'Collapse' : 'Expand'}
              </button>
            </div>
          </div>

          <div className="p-5">
            <div className="rounded-2xl border border-slate-200 bg-gradient-to-b from-slate-50 to-white p-4">
              <div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
                <div>
                  <p className="text-xs text-slate-500">Price</p>
                  <p className="text-lg font-semibold text-slate-900">${currency.price.toLocaleString()}</p>
                </div>
                <div className="text-right">
                  <p className="text-xs text-slate-500">Change 24h</p>
                  <p className={clsx("text-sm font-semibold", currency.percent_change_24h > 0 ? "text-emerald-700" : "text-rose-700")}>{formatPercentage(currency.percent_change_24h)}</p>
                </div>
              </div>

              <AreaChart width="100%" height={300} key={`area-chart-${expanded}`} data={currency.history}>
                <XAxis dataKey="timestamp" tickFormatter={() => ''} />
                <YAxis dataKey="price" domain={['dataMin', 'dataMax']} tickFormatter={(val) => val.toLocaleString()} width={120} />

                <Area dataKey="price" fillOpacity={0.3} />
              </AreaChart>
            </div>
          </div>
        </div>
    );
}