import { DataCard } from "@/components/ui/data-card";
import type { DashboardMetricCard, DashboardSummary } from "@/types";

/**
 * Dashboard KPI grid
 * ------------------
 * Renders the workbook-inspired dashboard scorecard as a single relational grid
 * so related metrics stay close to each other regardless of dashboard scope.
 */

function formatMetric(value: string | number, format?: DashboardSummary["metrics"]["primary"][number]["format"]) {
  const numeric = Number(value ?? 0);

  if (format === "currency") {
    return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(numeric);
  }

  if (format === "cpm") {
    return numeric.toFixed(2);
  }

  if (format === "rpm") {
    return typeof value === "string" && value.trim() === "-" ? "-" : `$${numeric.toFixed(2)}`;
  }

  if (format === "decimal") {
    return numeric.toFixed(2);
  }

  if (format === "number") {
    return new Intl.NumberFormat("en-US").format(numeric);
  }

  return value;
}

function getOrderedMetrics(metrics: DashboardSummary["metrics"]): DashboardMetricCard[] {
  const all = [...metrics.primary, ...metrics.secondary];
  const map = new Map(all.map((item) => [item.key, item]));

  const order = [
    "loads-booked",
    "cancelled",
    "outstanding",
    "paid-in-full",
    "dispatch-fee",
    "gross-profit",
    "total-miles",
    "avg-rpm",
    "projected-rpm",
    "projected-cpm",
    "actual-cpm",
    "cost-ops",
    "actual-cost",
  ];

  return order.map((key) => map.get(key)).filter(Boolean) as DashboardMetricCard[];
}

function getValueToneForAverageRpm(item: DashboardMetricCard) {
  const numeric = Number(item.value ?? 0);
  const criticalThreshold = item.criticalThreshold ?? 2.5;
  const warningThreshold = item.warningThreshold ?? 3;

  if (Number.isFinite(numeric) && numeric < criticalThreshold) {
    return "text-red-400";
  }

  if (Number.isFinite(numeric) && numeric < warningThreshold) {
    return "text-orange-300";
  }

  return "text-white";
}


function renderDarkMetricCard(item: DashboardMetricCard) {
  return (
    <div key={item.key} className="rounded-2xl border border-gray-900 bg-gray-900 p-5 shadow-sm">
      <div className="text-sm font-medium text-gray-300">{item.label}</div>
      <div className="mt-2 text-3xl font-semibold text-white">
        {formatMetric(item.value, item.format)}
      </div>
      {item.detail ? <div className="mt-1 text-sm text-gray-300">{item.detail}</div> : null}
    </div>
  );
}

function renderMetricCard(item: DashboardMetricCard) {
  if (item.key === "avg-rpm") {
    const valueTone = getValueToneForAverageRpm(item);
    return (
      <div key={item.key} className="rounded-2xl border border-black bg-black p-5 shadow-sm">
        <div className="text-sm font-medium text-gray-300">{item.label}</div>
        <div className={`mt-2 text-3xl font-semibold ${valueTone}`}>
          {formatMetric(item.value, item.format)}
        </div>
        {item.detail ? <div className="mt-1 text-sm text-gray-300">{item.detail}</div> : null}
      </div>
    );
  }

  if (item.highlight === "dark") {
    return renderDarkMetricCard(item);
  }

  return (
    <DataCard
      key={item.key}
      label={item.label}
      value={formatMetric(item.value, item.format)}
      detail={item.detail}
    />
  );
}

export function DispatchKpiGrid({ metrics }: { metrics: DashboardSummary["metrics"] }) {
  const items = getOrderedMetrics(metrics);

  return (
    <section className="space-y-3">
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-6">
        {items.map((item) => renderMetricCard(item))}
      </div>
    </section>
  );
}
