import Link from "next/link";
import "./TrailProgress.css";

type Props = {
  totalSteps: number;
  currentStep: number;
  furthestStep?: number;
  onStepClick?: (index: number) => void;
  isWalking?: boolean;
  onLeaveTrail?: () => void;
  backLink?: { to: string; text: string };
};

export function TrailProgress({
  totalSteps,
  currentStep,
  furthestStep,
  onStepClick,
  isWalking,
  onLeaveTrail,
  backLink,
}: Props) {
  const maxReached = furthestStep ?? currentStep;

  const linkTo = backLink?.to || "/walking";
  const linkText = backLink?.text || "← walking";

  const showLeftButton = isWalking;
  const showRightButton = isWalking && onLeaveTrail;

  return (
    <div className="TrailProgress">
      <div
        className={`TrailProgress-row ${!showLeftButton && !showRightButton ? "TrailProgress-row--completed" : ""}`}
      >
        {showLeftButton ? (
          <Link href={linkTo} className="TrailProgress-statusWalking">
            {linkText}
          </Link>
        ) : (
          <span className="TrailProgress-spacer">← walking</span>
        )}
        <div className="TrailProgress-path">
          {Array.from({ length: totalSteps }, (_, i) => {
            const isUnlocked = i <= maxReached;
            const isCompleted = i < currentStep;
            const isCurrent = i === currentStep;
            const isVisited = i > currentStep && i <= maxReached;

            return (
              <div key={i} className="TrailProgress-nodeWrapper">
                <div
                  className={`TrailProgress-node ${
                    isCompleted
                      ? "TrailProgress-node--completed"
                      : isCurrent
                        ? "TrailProgress-node--current"
                        : isVisited
                          ? "TrailProgress-node--visited"
                          : "TrailProgress-node--upcoming"
                  } ${isUnlocked && onStepClick ? "TrailProgress-node--clickable" : ""}`}
                  onClick={() => isUnlocked && onStepClick?.(i)}
                />
                {i < totalSteps - 1 && <div className="TrailProgress-line" />}
              </div>
            );
          })}
        </div>
        {showRightButton ? (
          <button onClick={onLeaveTrail} className="TrailProgress-statusLeave">
            abandon
          </button>
        ) : (
          <span className="TrailProgress-spacer">abandon</span>
        )}
      </div>
    </div>
  );
}
