"use client";

import {
  type JSX,
  useState,
  type HTMLAttributes,
  useEffect,
  useCallback,
} from "react";

interface TimeProps extends HTMLAttributes<HTMLParagraphElement> {
  showAMPM?: boolean;
}

export const Time = ({
  showAMPM = false,
  ...props
}: TimeProps): JSX.Element => {
  const formatTime = useCallback(
    (date: Date): string => {
      const hours = date.getHours() % 12 || 12;
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const ampm = showAMPM ? (date.getHours() >= 12 ? "PM" : "AM") : "";
      return `${hours}:${minutes} ${ampm}`;
    },
    [showAMPM]
  );

  const [time, setTime] = useState<string>(formatTime(new Date()));

  useEffect(() => {
    const id = setInterval(() => {
      setTime(formatTime(new Date()));
    }, 5000);
    return () => clearInterval(id);
  }, [formatTime]);

  return <p {...props}>{time}</p>;
};
