"use client";

import type { FinanceViewModel } from "@/lib/farmer-dashboard";
import { Card, CardHeader, CardTitle } from "@/components/ui/card";
import { Stepper, type StepperStep } from "@/components/ui/stepper";
import { tf } from "@/lib/i18n/dashboard-labels";
import type { AppLocale } from "@/lib/i18n/config";

export interface ApprovalPathStepperProps {
  stages: FinanceViewModel["stages"];
  locale: AppLocale;
  className?: string;
}

function formatStageTimestamp(iso: string, locale: AppLocale): string {
  try {
    return new Intl.DateTimeFormat(locale === "uz" ? "uz-UZ" : locale === "ru" ? "ru-RU" : "en-GB", {
      day: "numeric",
      month: "short",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(iso));
  } catch {
    return iso;
  }
}

function mapStagesToStepper(
  stages: FinanceViewModel["stages"],
  locale: AppLocale,
): StepperStep[] {
  const firstIncompleteIndex = stages.findIndex((s) => !s.completed);

  return stages.map((stage, index) => {
    let state: StepperStep["state"] = "pending";
    if (stage.completed) {
      state = "complete";
    } else if (index === firstIncompleteIndex) {
      state = "active";
    }

    return {
      id: `stage-${index}`,
      label: stage.label,
      description: stage.timestamp
        ? formatStageTimestamp(stage.timestamp, locale)
        : undefined,
      state,
    };
  });
}

export function ApprovalPathStepper({ stages, locale, className }: ApprovalPathStepperProps) {
  const steps = mapStagesToStepper(stages, locale);

  return (
    <Card padding="lg" className={className}>
      <CardHeader>
        <CardTitle>{tf("approvalPath", locale)}</CardTitle>
      </CardHeader>
      <Stepper steps={steps} ariaLabel={tf("approvalPath", locale)} />
    </Card>
  );
}
