import React, { useEffect } from "react";
import "./Notifications.css";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { getList } from "../../stores/slices/notificationSlice";
import { MdBlockFlipped } from "react-icons/md";
import { IoPhonePortraitOutline } from "react-icons/io5";
import { useTranslation } from "react-i18next";
import CLoading from "../../components/CLoading";

const Notifications: React.FC = () => {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();

  const getDefaultDates = () => {
    const dateTo = new Date();
    const dateFrom = new Date(dateTo);
    dateFrom.setDate(dateTo.getDate() - 30);

    return { dateFrom, dateTo };
  };

  const { notifications, loading } = useAppSelector(
    (state: RootState) => state.notification
  );

  useEffect(() => {
    dispatch(getList(getDefaultDates()));
  }, [dispatch]);

  return (
    <div className="notifications">
      <h3 className="notification__title">{t("notification.title")}</h3>

      <div className="notification__loading">
        {loading && notifications.length === 0 && <CLoading />}
      </div>

      {!loading && notifications.length === 0 && (
        <p>{t("notification.empty")}</p>
      )}

      <div className="notifications__list">
        {notifications.map((notification) => (
          <div className="notification" key={notification.id}>
            <div className="notification__caption">
              <MdBlockFlipped className="notification__caption__icon" />
              <p>{notification.caption}</p>
            </div>

            <p className="notification__text">{notification.text}</p>

            <div className="notification__date">
              <IoPhonePortraitOutline className="notification__date__icon" />
              {new Date(notification.date).toLocaleString()}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Notifications;
