import { format } from "date-fns";

import { buildSegments, segmentStyle, type DayMetrics } from "../../planner/timeline";

interface PlannerTimelineRowProps {
  days: DayMetrics[];
  dayDates: Date[];
  showTentative: boolean;
  titlePrefix?: string;
  onClick?: (dayIndex: number, day: Date) => void;
}

export function PlannerTimelineRow({
  days,
  dayDates,
  showTentative,
  titlePrefix,
  onClick,
}: PlannerTimelineRowProps) {
  const totalDays = dayDates.length;
  const segments = buildSegments(days, showTentative);

  return (
    <div className="planner-timeline">
      <div className="planner-day-grid" />
      {segments.map((segment, index) => {
        const startDay = dayDates[segment.startIndex];
        const endDay = dayDates[segment.endIndex];
        const rangeLabel =
          segment.startIndex === segment.endIndex
            ? format(startDay, "MMM d")
            : `${format(startDay, "MMM d")} – ${format(endDay, "MMM d")}`;
        const title = titlePrefix
          ? `${titlePrefix} • ${rangeLabel} → ${segment.tone.label}`
          : `${rangeLabel} → ${segment.tone.label}`;

        return (
          <div
            className={`planner-bar ${segment.tone.className}`}
            key={`${segment.startIndex}-${segment.endIndex}-${index}`}
            onClick={
              onClick
                ? () => onClick(segment.startIndex, dayDates[segment.startIndex])
                : undefined
            }
            onKeyDown={undefined}
            role={onClick ? "button" : undefined}
            style={segmentStyle(segment, totalDays)}
            tabIndex={onClick ? 0 : undefined}
            title={title}
          >
            {segment.tone.label ? <span className="planner-bar-label">{segment.tone.label}</span> : null}
          </div>
        );
      })}
    </div>
  );
}
