import React, { useEffect, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';

import { Link } from '@mui/material';
import { makeStyles } from 'tss-react/mui';

import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import pluralize from 'pluralize';

import { canAccess } from './Auditlog.jsx';
import { AUDIT_LOG_BASE } from './store/constants';
import { getAuditLogs } from './store/organizationSlice/thunks';

dayjs.extend(utc);

const useStyles = makeStyles()(theme => ({
  body: {
    fontWeight: 500,
    paddingBottom: 12,
    fontSize: 14
  },
  accessDeny: {
    color: theme.palette.text.muted,
    fontStyle: 'italic'
  },
  accessDenyView: {
    color: theme.palette.link.muted,
    'i, i:hover': {
      marginLeft: 4,
      fontSize: '16px !important',
      color: theme.palette.link.muted
    }
  },
  link: {
    textDecoration: 'none',
    fontWeight: 500
  }
}));

export const EntryPoint = () => {
  const { classes } = useStyles();
  const dispatch = useDispatch();
  const yesterday = useMemo(() => dayjs().subtract(1, 'day').utc().startOf('day'), []);
  const [total, setTotal] = useState();
  const [hasAccess, setHasAccess] = useState();

  useEffect(() => {
    setHasAccess(canAccess());
  }, []);

  useEffect(() => {
    if (!hasAccess) return;
    dispatch(getAuditLogs({ startDate: yesterday.format(), page: 1, perPage: 1000 }))
      .unwrap()
      .then(response => {
        const total = response?.payload?.total ?? 0;
        setTotal(total);
      });
  }, [dispatch, hasAccess, yesterday]);

  const totalEventsMessage =
    total !== undefined ? (
      <>
        <div className={`${classes.body} audit-log-entrypoint_body`}>
          There are{' '}
          <Link className={`${classes.link} audit-log-entrypoint_link`} href={`/${AUDIT_LOG_BASE}?startDate=${yesterday.format('YYYY-MM-DD')}`}>
            {total}
          </Link>{' '}
          {pluralize('event', total)} in the audit logs since yesterday.
        </div>
        <div>
          <Link className={`${classes.link} audit-log-entrypoint_link`} href={`/${AUDIT_LOG_BASE}`}>
            View Audit log
          </Link>
        </div>
      </>
    ) : (
      <div className="dash-loading">
        <i className="icon icon-spinner icon-spin" />
      </div>
    );

  const noAccessMessage = (
    <>
      <div className={`${classes.body} ${classes.accessDeny} audit-log-entrypoint_body`}>You do not have access to the audit log</div>
      <div className={`${classes.body} ${classes.accessDenyView} audit-log-entrypoint_accessDenyView`}>
        View Audit log{' '}
        <i
          rel="tooltip"
          data-placement="right"
          data-original-title="To access the audit log, contact an admin to gain access."
          className="bi bi-question-circle-fill"
        />
      </div>
    </>
  );

  return (
    <div className="audit-log-entrypoint">
      <h2 className="audit-log-entrypoint_title">Audit log</h2>
      {hasAccess ? totalEventsMessage : noAccessMessage}
    </div>
  );
};

export default EntryPoint;
