import { ReorderButton, AddButton, DeleteButton } from "@/app/EditButtons";
import { TrailStopCard } from "./TrailStopCard";
import { AccentButton } from "./AccentButton";
import { useEditMode } from "./EditModeContext";
import "./TrailStop.css";
import type { TrailStop as TrailStopType } from "@/data/queries";

type Props = {
  stop: TrailStopType;
  index: number;
  totalStops: number;
  isStepCompleted: boolean;
  isCurrent: boolean;
  isNextCurrent: boolean;
  isVisited: boolean;
  isClickable: boolean;
  isReorderActive?: boolean;
  onGoToStop: (index: number) => void;
  onContinue: () => void;
};

export function TrailStop({
  stop,
  index,
  totalStops,
  isStepCompleted,
  isCurrent,
  isNextCurrent,
  isVisited,
  isClickable,
  isReorderActive = false,
  onGoToStop,
  onContinue,
}: Props) {
  const editContext = useEditMode();
  const isEditing = !!editContext;

  const handleGoToStop = (newIndex: number) => {
    onGoToStop(newIndex);
  };

  const stopLabel = `Stop ${index + 1}${stop.title ? `: ${stop.title}` : ""}${
    isCurrent ? " (current)" : isStepCompleted ? " (completed)" : isVisited ? " (visited)" : ""
  }`;

  return (
    <div>
      <div
        className={`TrailStop ${
          isStepCompleted
            ? "TrailStop--completed"
            : isCurrent
              ? "TrailStop--current"
              : isVisited
                ? "TrailStop--visited"
                : ""
        } ${isClickable && !isCurrent ? "TrailStop--clickable" : ""} ${isReorderActive && isEditing ? "TrailStop--reorderActive" : ""} ${isEditing ? "TrailStop--editing" : ""}`}
        onClick={() => {
          if (isClickable && !isCurrent) {
            onGoToStop(index);
          }
        }}
        onKeyDown={(e) => {
          if (isClickable && (e.key === "Enter" || e.key === " ") && e.target === e.currentTarget) {
            e.preventDefault();
            onGoToStop(index);
          }
        }}
        onFocus={() => {
          if (!isCurrent) {
            onGoToStop(index);
          }
        }}
        tabIndex={isClickable && !isEditing ? 0 : undefined}
        role={isClickable && !isEditing ? "button" : undefined}
        aria-label={isClickable && !isEditing ? stopLabel : undefined}
      >
        {/* Opaque background - matches page background */}
        <div className="TrailStop-bg" />

        <div className="TrailStop-content">
          {/* Stop content first for logical tab order */}
          <div>
            <TrailStopCard
              stop={stop}
              stepNumber={index + 1}
              totalStops={totalStops}
              isCurrent={isCurrent}
            />
          </div>

          {/* View mode: done button */}
          {isCurrent && !isEditing && (
            <div className="TrailStop-actions">
              <AccentButton
                onClick={() => {
                  onContinue();
                }}
                size="large"
              >
                {stop.buttonText || "done that"}
              </AccentButton>
            </div>
          )}

          {/* Edit mode controls - after content for tab order */}
          {isEditing && editContext && (
            <>
              {/* Delete control - visually top right */}
              <div className="TrailStop-deleteButton">
                <DeleteButton
                  onClick={(e) => {
                    e.stopPropagation();
                    if (totalStops === 1) {
                      alert("you need at least one stop");
                      return;
                    }
                    const isEmpty = !stop.title.trim() && !stop.content.trim();
                    const shouldDelete = isEmpty || confirm("delete this stop?");

                    if (shouldDelete) {
                      if (isCurrent && index > 0) {
                        handleGoToStop(index - 1);
                      }
                      editContext.deleteStop(stop.tid);
                    }
                  }}
                  title="delete stop"
                />
              </div>

              {/* Reorder controls - only on current stop */}
              {isCurrent && (
                <div className="TrailStop-reorderControls">
                  {index > 0 && (
                    <ReorderButton
                      onClick={(e) => {
                        e.stopPropagation();
                        editContext.moveStop(stop.tid, "up");
                        handleGoToStop(index - 1);
                      }}
                      title="move up"
                    >
                      ↑
                    </ReorderButton>
                  )}
                  {index < totalStops - 1 && (
                    <ReorderButton
                      onClick={(e) => {
                        e.stopPropagation();
                        editContext.moveStop(stop.tid, "down");
                        handleGoToStop(index + 1);
                      }}
                      title="move down"
                    >
                      ↓
                    </ReorderButton>
                  )}
                </div>
              )}

              {/* Insert after button - visually between this stop and next.
                  Show if this stop is current, next stop is current (so it appears above current),
                  or it's the last stop with content */}
              {(isCurrent ||
                isNextCurrent ||
                (index === totalStops - 1 && (stop.title.trim() || stop.content.trim()))) &&
                totalStops < 12 && (
                  <div
                    className={`TrailStop-insertButton ${index === totalStops - 1 ? "TrailStop-insertButton--final" : "TrailStop-insertButton--between"}`}
                  >
                    <AddButton
                      onClick={(e) => {
                        e.stopPropagation();
                        editContext.addStop(index);
                        handleGoToStop(index + 1);
                      }}
                      title="add stop after"
                    />
                  </div>
                )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
