import moment from "moment-jalaali";
import { type FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import type { TaskTimeEntryType } from "../../../task/types/TaskTimeTypes";
import { formatElapsedTime, getEntryDurationSeconds } from "./utils";

type Props = {
  entry: TaskTimeEntryType;
  isActive: boolean;
};

const TimeListItem: FC<Props> = ({ entry, isActive }) => {
  const { t } = useTranslation("global");
  const [durationSeconds, setDurationSeconds] = useState(() => getEntryDurationSeconds(entry));

  useEffect(() => {
    if (!isActive) {
      setDurationSeconds(getEntryDurationSeconds(entry));
      return;
    }

    const updateDuration = () => {
      setDurationSeconds(getEntryDurationSeconds(entry));
    };

    updateDuration();
    const intervalId = window.setInterval(updateDuration, 1000);

    return () => {
      window.clearInterval(intervalId);
    };
  }, [entry.startedAt, entry.endedAt, entry.duration, isActive]);

  const startLabel = moment(entry.startedAt).format("jYYYY/jMM/jDD HH:mm");
  const endLabel = entry.endedAt ? moment(entry.endedAt).format("jYYYY/jMM/jDD HH:mm") : null;

  return (
    <div className="flex gap-1 h-[27px] items-center">
      <div className="group flex justify-between flex-1 h-full hover:bg-white hover:bg-opacity-10 items-center px-2 relative">
        <div className="text-xs truncate">
          {startLabel}
          {endLabel ? ` - ${endLabel}` : ` (${t("taskmanager.task_detail.tracking_active")})`}
        </div>
        <div className="font-mono text-xs font-bold text-[#01347A] shrink-0 mr-2">
          {formatElapsedTime(durationSeconds)}
        </div>
      </div>
    </div>
  );
};

export default TimeListItem;
