import { CostBreakdown } from "@/types/session/session";
import {
  getDynamicFlatFeePricing,
  toPerMinuteRateDisplay,
} from "@/modules/chargepointModule/connectorModule/helper";

type RateMinimalProps = {
  readonly breakdown?: CostBreakdown[] | null;
  readonly currency?: string | null | undefined;
  readonly fallback?: string | null | undefined;
};

const formatCurrency = (amount: number, currency?: string) => {
  try {
    return new Intl.NumberFormat("id-ID", {
      style: "currency",
      currency: currency || "IDR",
      maximumFractionDigits: 0,
    }).format(amount);
  } catch {
    return `${currency || "IDR"} ${Math.round(amount).toString()}`;
  }
};

const toPercent = (tax: number) => {
  const percent = tax <= 1 ? tax * 100 : tax;
  return `${Math.round(percent)}%`;
};

const resolveUnit = (item: CostBreakdown) => {
  if (item.unit) return item.unit;
  if (item.type === "ENERGY") return "kWh";
  if (item.type === "FLAT") return "session";
  if (item.type === "TIME" || item.type === "IDLE") return "hour";
  return "unit";
};

const isFlatFee = (item: CostBreakdown) => String(item.type || "").toUpperCase() === "FLAT";

const RateMinimal = ({ breakdown, currency, fallback }: RateMinimalProps) => {
  const items = Array.isArray(breakdown) ? breakdown : [];
  const rateName = items[0]?.rate_name;

  if (items.length === 0) {
    return (
      <div className="rounded-md border border-stroke bg-transparent p-3">
        <p className="text-sm font-semibold text-black dark:text-white">{fallback || "-"}</p>
      </div>
    );
  }

  return (
    <div className="rounded-md border border-stroke bg-transparent p-3">
      {/* {rateName ? (
        <div className="mb-2 text-xs font-medium uppercase tracking-wide text-slate-500 dark:text-slate-400">{rateName}</div>
      ) : null} */}
      <div className="flex flex-wrap gap-2">
        {items.map((item, idx) => {
          const displayRate = toPerMinuteRateDisplay(item.type, item.unit_price, resolveUnit(item));
          const price = formatCurrency(displayRate.unitPrice, currency || undefined);
          const tax = toPercent(item.tax);
          const flatFee = isFlatFee(item);
          const flatFeePricing = flatFee
            ? getDynamicFlatFeePricing(item.unit_price, currency || "IDR")
            : null;
          return (
            <span
              key={`${item.type}-${idx}`}
              className="inline-flex flex-col gap-1 rounded-md border border-stroke bg-gray-50 px-3 py-2 text-xs font-medium text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"
            >
              <span className="text-[10px] uppercase tracking-wide text-slate-500 dark:text-slate-400">
                {item.type}
              </span>
              <span>•</span>
              <span className={flatFee ? "max-w-[300px] leading-snug" : undefined}>
                {flatFeePricing?.description ?? `${price}/${displayRate.unit}`}
              </span>
              <span>{tax}</span>
            </span>
          );
        })}
      </div>
    </div>
  );
};

export default RateMinimal;
