import React, { useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';

import * as selectors from '../redux/selectors';
import * as actions from '../redux/slices';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { canSelectAccount } from '@/modules/analytics/general/helpers';

import ConfirmDialog from '@/modules/analytics/common/components/muiCustomComponents/ConfirmDialog';
import Failure from '@/modules/analytics/general/components/Failure';
import InfoNeedSelectAccount from '@/modules/analytics/general/components/InfoNeedSelectAccount';
import Loader from '@/modules/analytics/general/components/Loader';
import { Grid } from '@/mui/components';

import styles from './General.module.scss';

const SELECTED_ANALYTIC_QUERY = 'selectedAnalytic';
const PUBLISHER_NAME_QUERY = 'publisherName';
const SALESFORSE_ID_QUERY = 'salesforceId';

function GeneralAnalytics() {
  const dispatch = useDispatch();

  const menu = useSelector(selectors.getMenuSelector);
  const selectedAnalytic = useSelector(selectors.selectedAnalyticSelector);
  const publisherName = useSelector(selectors.publisherNameSelector);
  const salesforceId = useSelector(selectors.salesforceIdSelector);
  const isLoadingUrl = useSelector(selectors.isLoadingUrlSelector);
  const lookerReportUrl = useSelector(selectors.lookerReportUrlSelector);
  const statusOverallFailure = useSelector(selectors.statusOverallFailureSelector);
  const statusShowPopup = useSelector(selectors.statusShowPopupSelector);
  const statusPopupMessage = useSelector(selectors.statusPopupMessageSelector);

  const router = useRouter();
  const iframeRef = useRef(null);
  const userPermissions = useSelector(getUserPermissionsSelector);

  // get looker status
  useEffect(() => {
    dispatch(actions.getStatusAction());
  }, []);

  // if not query params redirect to first menu item
  useEffect(() => {
    const params = router.query;
    const shouldRedirectToFirstMenu =
      menu?.generalMenu?.length &&
      (!Object.keys(params).length || !Object.keys(params).includes(SELECTED_ANALYTIC_QUERY));

    if (shouldRedirectToFirstMenu) {
      const { href } = menu.generalMenu[0];
      router.push(href);
    }
  }, [JSON.stringify(menu)]);

  // set query params to store
  useEffect(() => {
    const params = router.query;
    const allowedQuery = [SELECTED_ANALYTIC_QUERY, PUBLISHER_NAME_QUERY, SALESFORSE_ID_QUERY];
    const selected = allowedQuery.reduce((acc, value) => {
      acc[value] = params[value] ? params[value] : '';
      return acc;
    }, {});

    if (Object.keys(selected).length) {
      dispatch(
        actions.setFieldAction({
          ...selected,
          account: {
            label: selected.publisherName,
            id: selected.salesforceId,
            salesforceId: selected.salesforceId,
          },
        }),
      );
    }
  }, [router.query]);

  // get looker url
  useEffect(() => {
    if (typeof statusOverallFailure !== 'undefined' && !statusOverallFailure && (selectedAnalytic || publisherName)) {
      dispatch(actions.getLookerUrlAction());
    }
  }, [statusOverallFailure, selectedAnalytic, publisherName, JSON.stringify(menu)]);

  useEffect(() => {
    const setIFrameLoaded = () => dispatch(actions.setFieldAction({ isLoadingUrl: false }));

    iframeRef.current?.addEventListener('load', () => setIFrameLoaded());
    return () => {
      iframeRef.current?.removeEventListener('load', () => setIFrameLoaded());
    };
  }, [lookerReportUrl]);

  return (
    <Grid container className={styles.Wrapper}>
      {statusOverallFailure && <Failure />}

      {!statusOverallFailure && (
        <>
          {canSelectAccount(userPermissions) && !salesforceId && <InfoNeedSelectAccount />}

          {isLoadingUrl && <Loader />}

          {lookerReportUrl && (
            <iframe
              ref={iframeRef}
              title="looker-report"
              className={styles.Iframe}
              src={lookerReportUrl}
              allowFullScreen
              scrolling="no"
            />
          )}
        </>
      )}

      <ConfirmDialog
        title="Info"
        body={statusPopupMessage}
        isOpen={statusShowPopup}
        confirmButtonText="Close"
        onConfirm={() => dispatch(actions.setFieldAction({ statusShowPopup: false }))}
        onClose={() => dispatch(actions.setFieldAction({ statusShowPopup: false }))}
      />
    </Grid>
  );
}

export default GeneralAnalytics;
