import { useRef } from "react";
import {
  DEFAULT_IMAGE_GENERATION_EXPECTED_DURATION_MS,
  formatEstimatedRemainingLabel,
  useSmoothedProgress,
} from "../../hooks/useSmoothedProgress";

interface EcommerceProgressBarProps {
  status: "idle" | "generating" | "done" | "failed" | string;
  label?: string;
}

function mapStatus(status: string): "running" | "completed" | "failed" {
  if (status === "done") return "completed";
  if (status === "failed") return "failed";
  if (status === "generating" || status === "modeling") return "running";
  return "running";
}

export function EcommerceProgressBar({
  status,
  label,
}: EcommerceProgressBarProps) {
  const startedAtRef = useRef(Date.now());
  const mappedStatus = mapStatus(status);
  const progress = mappedStatus === "running" ? 50 : 100;
  const smoothed = useSmoothedProgress(progress, mappedStatus, {
    progressSource: mappedStatus === "running" ? "estimated" : "real",
    startedAt: startedAtRef.current,
    expectedDurationMs: DEFAULT_IMAGE_GENERATION_EXPECTED_DURATION_MS,
  });
  const remainingLabel =
    mappedStatus === "running"
      ? formatEstimatedRemainingLabel({
          nowMs: Date.now(),
          startedAt: startedAtRef.current,
          expectedDurationMs: DEFAULT_IMAGE_GENERATION_EXPECTED_DURATION_MS,
        })
      : null;

  if (status === "idle") return null;

  return (
    <div className="ecommerce-progress-bar">
      <span className="ecommerce-progress-bar__label">
        {label || "AI 正在生成"}
        {remainingLabel ? ` / ${remainingLabel}` : ""}
      </span>
      <div className="ecommerce-progress-bar__track">
        <div
          className="ecommerce-progress-bar__fill"
          style={{ width: `${smoothed}%` }}
        />
      </div>
      <span className="ecommerce-progress-bar__value">{smoothed}%</span>
    </div>
  );
}
