import { useEffect, useState } from 'react';

type Props = {
  workedHours: number; // Number in hour decimal format
  lastStartEntry: string | undefined;
  runningClock: boolean;
};

const processTime = (decimalHour: number) => {
  const seconds = Math.round((((decimalHour % 1) * 60) % 1) * 60); // Get the remaining seconds
  return {
    hours: Math.floor(decimalHour), // Get the whole hour
    minutes: Math.floor((decimalHour % 1) * 60) + (seconds === 60 ? 1 : 0), // Get the remaining minutes
    seconds: seconds === 60 ? 0 : seconds,
  };
};

export const useChronometer = (props: Props) => {
  const { workedHours, lastStartEntry, runningClock } = props;

  const getInitialTime = () => {
    if (!runningClock || !lastStartEntry) {
      return workedHours;
    }
    const elapsedTime = Math.abs(
      new Date().getTime() - new Date(lastStartEntry).getTime(),
    );
    return workedHours + elapsedTime / 1000 / 3600;
  };
  const [time, setTime] = useState(getInitialTime);

  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;

    if (runningClock) {
      const lastStartEntryDate = lastStartEntry
        ? new Date(lastStartEntry)
        : new Date();
      const currentElapsedTime = Math.abs(
        new Date().getTime() - lastStartEntryDate.getTime(),
      );
      const initialTotalHours = workedHours + currentElapsedTime / 1000 / 3600;
      setTime(initialTotalHours);

      timer = setInterval(() => {
        const elapsedTime = Math.abs(
          new Date().getTime() - lastStartEntryDate.getTime(),
        );
        const totalHours = workedHours + elapsedTime / 1000 / 3600;
        setTime(totalHours);
      }, 1000);
    } else {
      setTime(workedHours);
    }

    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [lastStartEntry, runningClock, workedHours]);

  return processTime(time);
};
