import { EmptyState, Panel } from "@/components/shared/panel";
import { DemographicMap } from "./demographic-map";
import type { SummaryLoadState, UserNationalityItem } from "./types";

function countryLabel(value: string) {
  const normalized = value.trim();
  if (normalized.toLowerCase() === "id") return "Indonesia";
  if (normalized.toLowerCase() === "cn") return "China";
  return normalized;
}

function countryBadge(value: string) {
  const normalized = value.trim();
  return normalized.length <= 3
    ? normalized.toUpperCase()
    : normalized.slice(0, 2).toUpperCase();
}

export function CustomerDemographicCard({
  summary,
}: {
  summary: SummaryLoadState<UserNationalityItem[]>;
}) {
  const countries = [...(summary.data ?? [])].sort(
    (left, right) => right.count - left.count,
  );
  const total = countries.reduce((sum, country) => sum + country.count, 0);

  return (
    <Panel
      title="Customers Demographic"
      description="Number of customers by country"
    >
      <DemographicMap countries={countries} />
      {summary.error ? (
        <EmptyState
          title="Demographic data unavailable"
          description={summary.error}
        />
      ) : countries.length === 0 ? (
        <EmptyState
          title="No demographic data"
          description="The nationality summary returned no customers."
        />
      ) : (
        <div className="space-y-4">
          {countries.slice(0, 5).map((country) => {
            const percent =
              total > 0 ? Math.round((country.count / total) * 100) : 0;
            return (
              <div
                key={country.country}
                className="flex items-center gap-3"
              >
                <span
                  aria-hidden="true"
                  className="grid size-8 shrink-0 place-items-center rounded-full bg-muted text-xs font-semibold text-muted-foreground"
                >
                  {countryBadge(country.country)}
                </span>
                <div className="w-24 shrink-0">
                  <p className="truncate font-medium">
                    {countryLabel(country.country)}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {country.count.toLocaleString("id-ID")} customers
                  </p>
                </div>
                <div
                  className="h-2 flex-1 rounded-full bg-muted"
                  aria-label={`${percent}% of customers`}
                >
                  <div
                    className="h-2 rounded-full bg-primary"
                    style={{ width: `${percent}%` }}
                  />
                </div>
                <span className="w-10 text-right text-sm">{percent}%</span>
              </div>
            );
          })}
        </div>
      )}
    </Panel>
  );
}
