"use client";

import { Check, XCircle } from "lucide-react";
import type { OrderStage } from "@/lib/chat/types";
import { cn } from "@/lib/utils";
import { useChatBlocks } from "../ChatBlockContext";

const STEPS: Exclude<OrderStage, "cancelled">[] = [
  "placed",
  "confirmed",
  "loading",
  "dispatched",
  "delivered",
  "completed",
];

/** Horizontal progress through the order stages; `cancelled` replaces it with a banner. */
export default function StatusStepper({ stage }: { stage: OrderStage }) {
  const { copy } = useChatBlocks();

  if (stage === "cancelled") {
    return (
      <div className="flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-2 text-[11px] font-semibold text-red-700 ring-1 ring-red-100">
        <XCircle size={14} aria-hidden /> {copy.orderStages.cancelled}
      </div>
    );
  }

  const current = Math.max(0, STEPS.indexOf(stage));

  return (
    <ol aria-label={copy.orderProgress} className="flex items-start">
      {STEPS.map((step, i) => {
        const done = i < current || (i === current && step === "completed");
        const active = i === current;
        return (
          <li
            key={step}
            aria-current={active ? "step" : undefined}
            className="relative flex min-w-0 flex-1 flex-col items-center text-center"
          >
            {i > 0 ? (
              <span
                aria-hidden
                className={cn(
                  "absolute right-1/2 top-2.5 h-0.5 w-full -translate-y-1/2",
                  i <= current ? "bg-[#CC1414]" : "bg-gray-200"
                )}
              />
            ) : null}
            <span
              className={cn(
                "relative z-10 flex h-5 w-5 items-center justify-center rounded-full text-[9px] font-bold ring-2 ring-white",
                done
                  ? "bg-[#CC1414] text-white"
                  : active
                    ? "bg-white text-[#CC1414] ring-[#CC1414]"
                    : "bg-gray-200 text-gray-500"
              )}
            >
              {done ? <Check size={11} aria-hidden /> : i + 1}
            </span>
            <span
              className={cn(
                "mt-1 w-full truncate px-0.5 text-[9px] leading-tight",
                active ? "font-semibold text-gray-900" : "text-gray-500"
              )}
            >
              {copy.orderStages[step]}
            </span>
          </li>
        );
      })}
    </ol>
  );
}
