import { useState, useEffect } from 'react';
import { differenceInSeconds, formatDistanceToNowStrict } from 'date-fns';

import { ContactsProps } from '@/types/types.ts';

type LastActiveTimeProps = {
  contact: ContactsProps;
};

const LastActiveTime = ({ contact }: LastActiveTimeProps) => {
  const [timeAgo, setTimeAgo] = useState('');

  useEffect(() => {
    const updateTime = () => {
      if (!contact?.last_message_time) {
        return;
      }
      const lastActiveDate = new Date(contact.last_message_time);
      const secondsDiff = differenceInSeconds(new Date(), lastActiveDate);

      if (secondsDiff < 60) {
        setTimeAgo('now');
        return;
      }

      setTimeAgo(formatDistanceToNowStrict(lastActiveDate));
    };
    updateTime();

    const intervalId = setInterval(updateTime, 60000);

    return () => clearInterval(intervalId);
  }, [contact?.last_message_time]);

  return <span className="text-xs font-bold text-gray-500">{timeAgo}</span>;
};

export default LastActiveTime;
