import { useEffect, useState } from 'react';
import dayjs from 'dayjs';

import ssoEmailStorageManager from '../helpers/ssoEmailStorageManager';

const EXPIRED_DAYS = 30;

function useSsoLocalStorageEmails() {
  const [emails, setEmails] = useState([]);

  const handleUpdate = (emailsToUpdate) => {
    setEmails(emailsToUpdate);
    ssoEmailStorageManager.setEmails(emailsToUpdate);
  };

  const handleSaveEmailToLocalStorage = (email) => {
    const isExist = emails.some((o) => o.label === email);

    if (isExist) {
      handleUpdate(
        emails.map((o) => ({
          ...o,
          createdAt: o.label === email ? Date.now() : o.createdAt,
        })),
      );
    } else {
      handleUpdate(
        [].concat(emails, {
          label: email,
          createdAt: Date.now(),
        }),
      );
    }
  };

  useEffect(() => {
    const filteredByExpired = ssoEmailStorageManager
      .getEmails()
      .filter((email) => dayjs(email.createdAt).isBefore(dayjs(email.createdAt).add(EXPIRED_DAYS, 'd')));
    handleUpdate(filteredByExpired);
  }, []);

  return {
    emails: emails.reverse(),
    saveEmailToLocalStorage: handleSaveEmailToLocalStorage,
  };
}

export default useSsoLocalStorageEmails;
