import { type FC, useMemo } from "react";
import { useTranslation } from "react-i18next";
import type { TaskTimeEntryType } from "../../../task/types/TaskTimeTypes";
import TimeListItem from "./TimeListItem";
import { getActiveTimeEntry, sortTaskTimes } from "./utils";

type Props = {
  times?: TaskTimeEntryType[];
};

const TimeList: FC<Props> = ({ times = [] }) => {
  const { t } = useTranslation("global");
  const sortedTimes = useMemo(() => sortTaskTimes(times), [times]);
  const activeEntry = useMemo(() => getActiveTimeEntry(times), [times]);

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

  return (
    <div className="mt-6">
      <div className="text-sm font-bold">{t("taskmanager.task_detail.time_tracking")}</div>

      <div className="mt-4 flex flex-col gap-2">
        {sortedTimes.map((entry) => (
          <TimeListItem key={entry.id} entry={entry} isActive={activeEntry?.id === entry.id} />
        ))}
      </div>
    </div>
  );
};

export default TimeList;
