import { useState, useEffect } from 'react';
import { formatDistanceToNow, differenceInSeconds } 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(formatDistanceToNow(lastActiveDate));
    };
    updateTime();

    const intervalId = setInterval(updateTime, 60000);

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

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

export default LastActiveTime;
