import { Crown, UserCheck, Sparkles, Moon } from "lucide-react";

export type CustomerSegment = "vip" | "regular" | "new" | "inactive";

export const SEGMENT_META: Record<
  CustomerSegment,
  { en: string; bn: string; cls: string; Icon: React.ElementType }
> = {
  vip: {
    en: "VIP",
    bn: "ভিআইপি",
    cls: "bg-amber-100 text-amber-800 border-amber-300 dark:bg-amber-900/30 dark:text-amber-200 dark:border-amber-700",
    Icon: Crown,
  },
  regular: {
    en: "Regular",
    bn: "নিয়মিত",
    cls: "bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-900/30 dark:text-blue-200 dark:border-blue-700",
    Icon: UserCheck,
  },
  new: {
    en: "New",
    bn: "নতুন",
    cls: "bg-green-100 text-green-800 border-green-300 dark:bg-green-900/30 dark:text-green-200 dark:border-green-700",
    Icon: Sparkles,
  },
  inactive: {
    en: "Inactive",
    bn: "নিষ্ক্রিয়",
    cls: "bg-gray-200 text-gray-700 border-gray-300 dark:bg-gray-700/40 dark:text-gray-300 dark:border-gray-600",
    Icon: Moon,
  },
};

export function SegmentBadge({
  segment,
  isBn,
  size = "sm",
}: {
  segment: CustomerSegment;
  isBn?: boolean;
  size?: "sm" | "md";
}) {
  const m = SEGMENT_META[segment];
  const Icon = m.Icon;
  const pad = size === "md" ? "px-2.5 py-1 text-xs" : "px-2 py-0.5 text-[11px]";
  return (
    <span
      className={`inline-flex items-center gap-1 rounded-full border font-semibold ${pad} ${m.cls}`}
    >
      <Icon className="h-3 w-3" />
      {isBn ? m.bn : m.en}
    </span>
  );
}

export type SegmentThresholds = {
  vipTotalPurchase: number;
  vipMonthlyOrders: number;
  regularMonthlyOrdersMin: number;
  newCustomerDays: number;
  inactiveDays: number;
};

export const DEFAULT_THRESHOLDS: SegmentThresholds = {
  vipTotalPurchase: 100000,
  vipMonthlyOrders: 20,
  regularMonthlyOrdersMin: 3,
  newCustomerDays: 30,
  inactiveDays: 90,
};

export function computeSegment(
  c: {
    created_at: string | Date;
    totalPurchase: number;
    monthlyOrders: number;
    lastPurchaseDate: string | Date | null;
  },
  t: SegmentThresholds,
): CustomerSegment {
  const now = Date.now();
  const dayMs = 86400000;
  const createdDays = (now - new Date(c.created_at).getTime()) / dayMs;
  const lastDays = c.lastPurchaseDate
    ? (now - new Date(c.lastPurchaseDate).getTime()) / dayMs
    : Infinity;

  if (c.totalPurchase >= t.vipTotalPurchase || c.monthlyOrders >= t.vipMonthlyOrders) {
    return "vip";
  }
  if (lastDays > t.inactiveDays && c.totalPurchase > 0) return "inactive";
  if (createdDays <= t.newCustomerDays && c.totalPurchase <= 0) return "new";
  if (c.monthlyOrders >= t.regularMonthlyOrdersMin) return "regular";
  if (createdDays <= t.newCustomerDays) return "new";
  if (c.totalPurchase > 0) return "regular";
  return "inactive";
}
