"use client";

import { FloatingAvatar } from "@/app/FloatingAvatar";
import { DeleteButton } from "@/app/EditButtons";
import "./TrailOverviewStop.css";
import { use } from "react";

type Walker = {
  did: string;
  handle: string;
  avatar?: string;
};

interface TrailOverviewStopProps {
  stop: {
    tid: string;
    title: string;
    walkersHere: Promise<Walker[]>;
  };
  index: number;
  isEditing: boolean;
  isLocked: boolean;
  isCurrent: boolean;
  totalStops: number;
  onTitleChange?: (stopId: string, title: string) => void;
  onDelete?: (stopId: string) => void;
  onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>, stopId: string) => void;
}

function WalkersHere({ walkers }: { walkers: Promise<Walker[]> }) {
  const walkersHere = use(walkers);

  if (walkersHere.length === 0) return null;

  return (
    <div className="TrailOverviewStop-walkers">
      {walkersHere.slice(0, 5).map((walker: Walker) => {
        return (
          <FloatingAvatar
            key={walker.did}
            src={walker.avatar}
            title={walker.handle}
            contained={true}
            opaque={true}
            handle={walker.handle}
          />
        );
      })}
      {walkersHere.length > 5 && (
        <span className="TrailOverviewStop-walkersExtra">+{walkersHere.length - 5}</span>
      )}
    </div>
  );
}

export function TrailOverviewStop({
  stop,
  index,
  isEditing,
  isLocked,
  isCurrent,
  totalStops,
  onTitleChange,
  onDelete,
  onKeyDown,
}: TrailOverviewStopProps) {
  if (isEditing) {
    return (
      <li className="TrailOverviewStop TrailOverviewStop--editing">
        <span className="TrailOverviewStop-number">{index + 1}</span>
        <input
          type="text"
          value={stop.title || ""}
          onChange={(e) => onTitleChange?.(stop.tid, e.target.value)}
          onKeyDown={(e) => onKeyDown?.(e, stop.tid)}
          className="TrailOverviewStop-titleInput"
          placeholder={`name this stop`}
        />
        <div className="TrailOverviewStop-actions">
          {totalStops > 1 && <DeleteButton onClick={() => onDelete?.(stop.tid)} title="delete" />}
        </div>
      </li>
    );
  }

  return (
    <li
      className={`TrailOverviewStop ${isLocked ? "TrailOverviewStop--locked" : ""} ${isCurrent ? "TrailOverviewStop--current" : ""}`}
    >
      <span className="TrailOverviewStop-number">{index + 1}</span>
      <span className="TrailOverviewStop-title">
        {stop.title || `stop ${index + 1}`}
        {isCurrent && <span className="TrailOverviewStop-indicator"> ← you were here</span>}
      </span>
      <WalkersHere walkers={stop.walkersHere} />
    </li>
  );
}
