"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

export type StageStatus = "completed" | "active" | "pending" | "error";

export interface Stage {
  id: string;
  label: string;
  description?: string;
  status: StageStatus;
}

export interface StageProgressProps extends React.HTMLAttributes<HTMLDivElement> {
  stages: Stage[];
  onStageClick?: (stage: Stage, index: number) => void;
  orientation?: "horizontal" | "vertical";
}

const stageStatusConfig: Record<StageStatus, { dotClass: string; labelClass: string; connectorClass: string }> = {
  completed: {
    dotClass: "bg-primary border-primary text-primary-foreground",
    labelClass: "text-primary font-semibold",
    connectorClass: "bg-primary",
  },
  active: {
    dotClass: "bg-white border-primary ring-4 ring-primary/20 text-primary",
    labelClass: "text-foreground font-semibold",
    connectorClass: "bg-border",
  },
  pending: {
    dotClass: "bg-white border-border text-muted-foreground",
    labelClass: "text-muted-foreground",
    connectorClass: "bg-border",
  },
  error: {
    dotClass: "bg-destructive border-destructive text-destructive-foreground",
    labelClass: "text-destructive font-semibold",
    connectorClass: "bg-border",
  },
};

const StageIcon = ({ status, index }: { status: StageStatus; index: number }) => {
  if (status === "completed") {
    return (
      <svg className="h-3.5 w-3.5" viewBox="0 0 14 14" fill="none">
        <path d="M2.5 7L5.5 10L11.5 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  }
  if (status === "error") {
    return (
      <svg className="h-3.5 w-3.5" viewBox="0 0 14 14" fill="none">
        <path d="M4 4L10 10M10 4L4 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      </svg>
    );
  }
  return <span className="text-xs font-bold">{index + 1}</span>;
};

const StageProgress = React.forwardRef<HTMLDivElement, StageProgressProps>(
  ({ className, stages, onStageClick, orientation = "horizontal", ...props }, ref) => {
    if (orientation === "vertical") {
      return (
        <div ref={ref} className={cn("flex flex-col", className)} {...props}>
          {stages.map((stage, idx) => {
            const config = stageStatusConfig[stage.status];
            const isLast = idx === stages.length - 1;
            return (
              <div key={stage.id} className="flex gap-3">
                {/* connector column */}
                <div className="flex flex-col items-center">
                  <button
                    type="button"
                    onClick={() => onStageClick?.(stage, idx)}
                    className={cn(
                      "flex h-8 w-8 shrink-0 items-center justify-center rounded-full border-2 transition-all duration-200",
                      config.dotClass,
                      onStageClick && "cursor-pointer hover:scale-110",
                      !onStageClick && "cursor-default"
                    )}
                  >
                    <StageIcon status={stage.status} index={idx} />
                  </button>
                  {!isLast && (
                    <div className={cn("w-0.5 flex-1 my-1 min-h-[1.5rem]", config.connectorClass)} />
                  )}
                </div>
                {/* content */}
                <div className={cn("pb-6", isLast && "pb-0")}>
                  <p className={cn("text-sm leading-8", config.labelClass)}>{stage.label}</p>
                  {stage.description && (
                    <p className="text-xs text-muted-foreground mt-0.5">{stage.description}</p>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      );
    }

    return (
      <div ref={ref} className={cn("relative flex items-center", className)} {...props}>
        {stages.map((stage, idx) => {
          const config = stageStatusConfig[stage.status];
          const isLast = idx === stages.length - 1;
          return (
            <React.Fragment key={stage.id}>
              <div className="flex flex-col items-center gap-2">
                <button
                  type="button"
                  onClick={() => onStageClick?.(stage, idx)}
                  className={cn(
                    "flex h-9 w-9 shrink-0 items-center justify-center rounded-full border-2 transition-all duration-200",
                    config.dotClass,
                    onStageClick && "cursor-pointer hover:scale-110 hover:shadow-md",
                    !onStageClick && "cursor-default"
                  )}
                >
                  <StageIcon status={stage.status} index={idx} />
                </button>
                <span className={cn("text-xs whitespace-nowrap", config.labelClass)}>
                  {stage.label}
                </span>
                {stage.description && (
                  <span className="text-xs text-muted-foreground whitespace-nowrap">
                    {stage.description}
                  </span>
                )}
              </div>
              {!isLast && (
                <div className={cn("h-0.5 flex-1 mx-2 mb-5 transition-colors duration-300", config.connectorClass)} />
              )}
            </React.Fragment>
          );
        })}
      </div>
    );
  }
);
StageProgress.displayName = "StageProgress";

export { StageProgress };
