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;

            const canNavigate = isUnlocked && onStepClick;

            return (
              <div key={i} className="TrailProgress-nodeWrapper">
                <button
                  type="button"
                  className={`TrailProgress-node ${
                    isCompleted
                      ? "TrailProgress-node--completed"
                      : isCurrent
                        ? "TrailProgress-node--current"
                        : isVisited
                          ? "TrailProgress-node--visited"
                          : "TrailProgress-node--upcoming"
                  } ${canNavigate ? "TrailProgress-node--clickable" : ""}`}
                  onClick={() => canNavigate && onStepClick(i)}
                  disabled={!canNavigate}
                  aria-label={`Go to stop ${i + 1}${isCurrent ? " (current)" : isCompleted ? " (completed)" : isVisited ? " (visited)" : ""}`}
                  aria-current={isCurrent ? "step" : undefined}
                />
                {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>
  );
}
