import { CheckCircle2 } from "lucide-react"

import { cn } from "@/lib/utils"
import {
  RUN_CANCELLED_COLOR,
  RUN_COMPLETED_COLOR,
  STAGE_STATUS_COLOR,
  STAGE_STATUS_LABEL,
  STAGE_STATUS_ORDER,
} from "@/lib/production-status-colors"
import { ProductionRunStatus, StageSummary } from "@/types/production"

/**
 * One segment per stage-status count (docs/21-FRONTEND-PHASE2.md §3). Completed runs render
 * a full teal strip + check; cancelled runs get a red accent instead of per-stage segments.
 */
export function StageProgressStrip({
  status,
  summary,
  className,
}: {
  status: ProductionRunStatus
  summary: StageSummary
  className?: string
}) {
  if (status === "Completed") {
    return (
      <div className={cn("flex h-2.5 items-center gap-1.5 rounded-full", className)}>
        <div className="h-2.5 flex-1 rounded-full" style={{ backgroundColor: RUN_COMPLETED_COLOR }} />
        <CheckCircle2 className="size-4 shrink-0" style={{ color: RUN_COMPLETED_COLOR }} />
      </div>
    )
  }

  const counts: Record<string, number> = {
    Waiting: summary.waiting,
    Ready: summary.ready,
    InProgress: summary.inProgress,
    Done: summary.done,
    Approved: summary.approved,
  }
  const total = STAGE_STATUS_ORDER.reduce((sum, key) => sum + counts[key], 0)

  return (
    <div
      className={cn("flex h-2.5 w-full overflow-hidden rounded-full bg-muted", className)}
      style={status === "Cancelled" ? { boxShadow: `0 0 0 2px ${RUN_CANCELLED_COLOR}` } : undefined}
    >
      {total === 0
        ? null
        : STAGE_STATUS_ORDER.map((key) => {
            const count = counts[key]
            if (count === 0) return null
            return (
              <div
                key={key}
                title={`${STAGE_STATUS_LABEL[key]}: ${count}`}
                style={{ backgroundColor: STAGE_STATUS_COLOR[key], width: `${(count / total) * 100}%` }}
              />
            )
          })}
    </div>
  )
}

export function StageStatusLegend({ className }: { className?: string }) {
  return (
    <div className={cn("flex flex-wrap items-center gap-x-4 gap-y-1.5", className)}>
      {STAGE_STATUS_ORDER.map((key) => (
        <div key={key} className="flex items-center gap-1.5 text-xs text-muted-foreground">
          <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: STAGE_STATUS_COLOR[key] }} />
          {STAGE_STATUS_LABEL[key]}
        </div>
      ))}
      <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
        <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: RUN_CANCELLED_COLOR }} />
        Cancelled
      </div>
      <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
        <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: RUN_COMPLETED_COLOR }} />
        Completed
      </div>
    </div>
  )
}
