import { EmptyState, Panel } from "@/components/shared/panel";
import { Chart } from "./chart";
import { summarizeUserGrowth } from "./user-growth-metrics";
import type { SummaryLoadState, UserGrowthSummary } from "./types";

function formatDate(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return new Intl.DateTimeFormat("en", {
    day: "2-digit",
    month: "short",
    timeZone: "UTC",
  }).format(date);
}

export function UserGrowthPanel({
  summary,
}: {
  summary: SummaryLoadState<UserGrowthSummary>;
}) {
  const metrics = summary.data
    ? summarizeUserGrowth(summary.data.points)
    : null;
  const average = new Intl.NumberFormat("id-ID", {
    maximumFractionDigits: 1,
  }).format(metrics?.averagePerRegistrationDay ?? 0);

  return (
    <Panel
      title="New User Growth"
      description="Daily new registrations this month"
    >
      {summary.error ? (
        <EmptyState
          title="Growth data unavailable"
          description={summary.error}
        />
      ) : !summary.data || summary.data.points.length === 0 ? (
        <EmptyState
          title="No growth data"
          description="The user growth summary returned no registrations."
        />
      ) : (
        <>
          <div className="mt-6 flex items-end gap-2">
            <span
              aria-hidden="true"
              className="mb-2 size-2.5 rounded-full bg-[var(--chart-4)]"
            />
            <p className="text-3xl font-semibold leading-none">
              {summary.data.totalCount.toLocaleString("id-ID")}
            </p>
            <p className="mb-0.5 text-sm text-muted-foreground">
              new registrations this month
            </p>
          </div>

          <div className="my-5 min-h-[235px] overflow-hidden rounded-xl bg-muted/50 dark:bg-black/20">
            <div className="-ml-5 -mr-2 h-full">
              <Chart
                appearance="compact"
                type="area"
                series={[
                  {
                    name: "New users",
                    data: summary.data.points.map((point) => point.count),
                  },
                ]}
                categories={summary.data.points.map((point) =>
                  formatDate(point.startTime),
                )}
                height={220}
                unit="users"
              />
            </div>
          </div>

          <div className="grid grid-cols-3 divide-x divide-border">
            <div className="px-2 text-center">
              <p className="text-lg font-semibold">{average}</p>
              <p className="mt-0.5 text-xs text-muted-foreground">
                Avg. per active day
              </p>
            </div>
            <div className="px-2 text-center">
              <p className="text-lg font-semibold">
                {metrics?.peakDay.toLocaleString("id-ID")}
              </p>
              <p className="mt-0.5 text-xs text-muted-foreground">Peak day</p>
            </div>
            <div className="px-2 text-center">
              <p className="text-lg font-semibold">
                {metrics?.registrationDays.toLocaleString("id-ID")}
              </p>
              <p className="mt-0.5 text-xs text-muted-foreground">
                Active days
              </p>
            </div>
          </div>
        </>
      )}
    </Panel>
  );
}
