import React, { useState, useEffect } from 'react';
import { Alert, Card, CardBody, Col, Row } from 'reactstrap';
import JKNotification from '../notification/JKNotification';
import FalconCardHeader from '../common/FalconCardHeader';
import Loader from '../common/Loader';
import { isIterableArray } from '../../helpers/utils';

import { fetchNotifications } from '../../store/features/notificationSlice';
import { useDispatch, useSelector } from 'react-redux';
import { useAuth } from '../../context/UserAuth';

const JKNotifications = () => {
  const { currentUser } = useAuth();
  const dispatch = useDispatch();
  const notifications = useSelector(state => state.notification.notifications);
  const loadingState = useSelector(state => state.notification.state);

  const LIMIT = 20;
  const [page, setPage] = useState(0);

  const loadNotifications = async () => {
    try {
      const options = {
        userId: currentUser.id,
        offset: page * LIMIT,
        limit: LIMIT
      };
      await dispatch(fetchNotifications(options)).unwrap();
      //setPage(prev => prev + 1);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    loadNotifications();
  }, []);

  return (
    <Card className="h-100">
      <FalconCardHeader title="Your Notifications">
        {/* <div className="fs--1">
          <Link className="text-sans-serif" to="#!" onClick={markAsRead}>
            Mark all as read
          </Link>
        </div> */}
      </FalconCardHeader>
      <CardBody className="p-0">
        {loadingState === 'loading' ? (
          <Loader />
        ) : isIterableArray(notifications) ? (
          notifications.map(notification => (
            <JKNotification notification={notification} key={notification.notification_id} />
          ))
        ) : (
          <Row className="p-card">
            <Col>
              <Alert color="info" className="mb-0">
                No notifications found!
              </Alert>
            </Col>
          </Row>
        )}
      </CardBody>
    </Card>
  );
};

export default JKNotifications;
