import type { AppLocale } from "@/lib/i18n/config";
import { td } from "@/lib/i18n/dashboard-labels";
import type { StepperStep, StepperStepState } from "@/components/ui/stepper";

export function resolveStepState(
  completed: boolean,
  isActive: boolean,
): StepperStepState {
  if (completed) return "complete";
  if (isActive) return "active";
  return "pending";
}

export function paymentRouteToStepperSteps(
  steps: Array<{ step: number; label: string; completed: boolean }>,
): StepperStep[] {
  const activeIndex = steps.findIndex((step) => !step.completed);

  return steps.map((step, index) => ({
    id: String(step.step),
    label: step.label,
    state: resolveStepState(
      step.completed,
      !step.completed && index === activeIndex,
    ),
  }));
}

export function deliveryStepsToStepperSteps(
  steps: Array<{ label: string; completed: boolean; timestamp?: string | null }>,
  locale: AppLocale,
): StepperStep[] {
  const activeIndex = steps.findIndex((step) => !step.completed);

  return steps.map((step, index) => ({
    id: `delivery-${index}`,
    label: step.label,
    description: step.timestamp
      ? formatShortDate(step.timestamp)
      : step.completed
        ? undefined
        : td("inputsDeliveryPending", locale),
    state: resolveStepState(
      step.completed,
      !step.completed && index === activeIndex,
    ),
  }));
}

export function formatShortDate(iso: string): string {
  try {
    return new Date(iso).toLocaleDateString(undefined, {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

export function formatCurrency(amount: number, currency: string): string {
  return `${amount.toLocaleString()} ${currency}`;
}

export function categoryToTabId(category: string): string {
  return category.toLowerCase().replace(/\s+/g, "-");
}
