import { format } from "date-fns";

import {
  buildProjectBarSegment,
  projectBarStyle,
  type ProjectBarSegment,
} from "../../planner/projectTimeline";

interface ProjectTimelineRowProps {
  dayDates: Date[];
  startDate: string;
  endDate: string;
  name: string;
  color: string;
  tentative: boolean;
  showTentative: boolean;
  onClick?: () => void;
}

export function ProjectTimelineRow({
  dayDates,
  startDate,
  endDate,
  name,
  color,
  tentative,
  showTentative,
  onClick,
}: ProjectTimelineRowProps) {
  const totalDays = dayDates.length;
  const segment = buildProjectBarSegment(
    dayDates,
    startDate,
    endDate,
    name,
    tentative,
    showTentative,
  );

  return (
    <div className="planner-timeline">
      <div className="planner-day-grid" />
      {segment ? (
        <ProjectBar segment={segment} color={color} dayDates={dayDates} onClick={onClick} totalDays={totalDays} />
      ) : null}
    </div>
  );
}

function ProjectBar({
  segment,
  totalDays,
  dayDates,
  color,
  onClick,
}: {
  segment: ProjectBarSegment;
  totalDays: number;
  dayDates: Date[];
  color: string;
  onClick?: () => void;
}) {
  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")}`;

  return (
    <div
      className={segment.className}
      onClick={onClick}
      role={onClick ? "button" : undefined}
      style={{
        ...projectBarStyle(segment, totalDays),
        background: color,
        borderTopColor: color,
      }}
      tabIndex={onClick ? 0 : undefined}
      title={`${segment.label} • ${rangeLabel}`}
    >
      <span className="planner-bar-label">{segment.label}</span>
    </div>
  );
}
