import React, { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { HelpOutline, PictureAsPdfRounded } from '@mui/icons-material';

import { CALENDAR_FILTER_VALUE } from '../constants';
import { PDF_EXPORT_HIDE_CONTENT } from '@/modules/analytics/common/constants';

import * as selectors from '../redux/selectors';
import * as actions from '../redux/slices';

import { DialogCalendarRange, Layout } from '@/modules/analytics/common/components';
import Chart from './Chart';
import Countries from './Countries';
import Devices from './Devices';
import Filters from './Filters';
import Tabs from './Tabs';
import Timezone from './Timezone';
import { CircularProgress, IconButton, Paper, Tooltip, Typography } from '@/mui/components';
import { CustomCsvFilled } from '@/mui/components/CustomIcon';

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

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

  const calendar = useSelector(selectors.calendarSelector);
  const calendarCustom = useSelector(selectors.calendarCustomSelector);
  const eventsOptions = useSelector(selectors.eventsOptionsSelector);
  const event = useSelector(selectors.eventSelector);
  const sessionsOptions = useSelector(selectors.sessionsOptionsSelector);
  const sessions = useSelector(selectors.sessionsSelector);
  const activeTab = useSelector(selectors.activeTabSelector);
  const users = useSelector(selectors.usersSelector);
  const totalMinutes = useSelector(selectors.totalMinutesSelector);
  const averageMinutes = useSelector(selectors.averageMinutesSelector);
  const averageMinutesPercent = useSelector(selectors.averageMinutesPercentSelector);
  const desktop = useSelector(selectors.desktopSelector);
  const mobile = useSelector(selectors.mobileSelector);
  const countries = useSelector(selectors.countriesSelector);
  const chartData = useSelector(selectors.chartDataSelector);
  const isExportPdfLoading = useSelector(selectors.isExportPdfLoadingSelector);

  const exportToCSV = (o) => dispatch(actions.exportToCSVAction(o));

  const [isCalendarOpen, setIsCalendarOpen] = useState(false);
  const contentRef = useRef(null);

  useEffect(() => {
    dispatch(actions.getCountriesFullListAction());
    dispatch(actions.getLiveEventsAction());
  }, []);

  const handleExportToPDF = () => dispatch(actions.exportToPDFAction(contentRef.current));

  const cleanData = () => {
    dispatch(
      actions.setFieldAction({
        users: null,
        totalMinutes: null,
        averageMinutes: null,
        averageMinutesPercent: null,
        desktop: {
          all: null,
          medium: null,
          large: null,
          xLarge: null,
        },
        mobile: {
          all: null,
          medium: null,
          small: null,
          xSmall: null,
        },
        countries: {
          all: null,
          items: [],
        },
        chartData: [],
      }),
    );
  };

  const handleFilterSetCalendar = (value) => {
    dispatch(
      actions.setFieldAction({
        calendar: value,
      }),
    );

    if (value === CALENDAR_FILTER_VALUE.custom) {
      setIsCalendarOpen(true);
      return;
    }

    dispatch(
      actions.setFieldAction({
        event: null,
        sessions: [],
      }),
    );

    cleanData();

    dispatch(actions.getLiveEventsAction());
  };

  const handleMenuItemClick = (itemValue) => {
    if (itemValue === CALENDAR_FILTER_VALUE.custom) {
      setIsCalendarOpen(true);
    }
  };

  const handleEventChange = (value) => {
    dispatch(
      actions.setFieldAction({
        event: value,
        sessions: [],
        sessionsOptions: [],
      }),
    );

    if (!value) {
      cleanData();
    }

    if (value) {
      dispatch(actions.getLiveEventByIdAction({ id: value.value }));
    }
  };

  const handleEventInputChange = (value) => {
    dispatch(actions.getLiveEventsAction({ search: value }));
  };

  const handleSessionsChange = (value) => {
    dispatch(
      actions.setFieldAction({
        sessions: value,
      }),
    );

    if (!value?.length) {
      cleanData();
    }

    dispatch(actions.getLivePerformanceTotalsAction());
    dispatch(actions.getChartDataAction());
  };

  const handleTabClick = (value) => {
    dispatch(actions.setFieldAction({ activeTab: value }));
    dispatch(actions.getChartDataAction());
  };

  return (
    <Layout ref={contentRef} contentClassName={styles.LiveDashboardLayout}>
      <section className={styles.Header}>
        <div className={styles.TitleWrap}>
          <div className={styles.TitleContent}>
            <Typography className={styles.Title} variant="h6Alt" color="text.primary" component="span" fontWeight={500}>
              Event Dashboard
            </Typography>

            <Tooltip
              title="See how your live events performed, minute by minute. Only finished events are available for display"
              placement="top"
            >
              <span>
                <HelpOutline fontSize="xSmall" htmlColor="info.main" className={styles.InfoIcon} />
              </span>
            </Tooltip>
          </div>

          <div className={styles.Exports} data-pdf-export={PDF_EXPORT_HIDE_CONTENT}>
            {isExportPdfLoading && (
              <CircularProgress
                size={14}
                color="inherit"
                classes={{
                  root: styles.LoadingSpinner,
                }}
              />
            )}

            {!isExportPdfLoading && (
              <IconButton onClick={handleExportToPDF}>
                <PictureAsPdfRounded />
              </IconButton>
            )}

            <IconButton onClick={exportToCSV}>
              <CustomCsvFilled />
            </IconButton>
          </div>
        </div>

        <div className={styles.Filters}>
          <Filters
            calendar={calendar}
            calendarCustom={calendarCustom}
            handleFilterSetCalendar={handleFilterSetCalendar}
            handleMenuItemClick={handleMenuItemClick}
            eventsOptions={eventsOptions}
            event={event}
            handleEventChange={handleEventChange}
            handleEventInputChange={handleEventInputChange}
            sessionsOptions={sessionsOptions}
            sessions={sessions}
            handleSessionsChange={handleSessionsChange}
          />
        </div>
      </section>

      <div className={styles.Content}>
        <section className={styles.ChartSection}>
          <Tabs
            activeTab={activeTab}
            handleTabClick={handleTabClick}
            users={users}
            totalMinutes={totalMinutes}
            averageMinutes={averageMinutes}
            averageMinutesPercent={averageMinutesPercent}
          />

          <Paper elevation={7} className={styles.Chart}>
            <Chart chartData={chartData} activeTab={activeTab} />
          </Paper>
        </section>

        <section className={styles.TablesSection}>
          <Devices desktop={desktop} mobile={mobile} />

          <Countries countries={countries} />

          <Timezone />
        </section>
      </div>

      <DialogCalendarRange
        open={isCalendarOpen}
        onClose={() => setIsCalendarOpen(false)}
        onDateSubmit={(dateRange) => {
          dispatch(
            actions.setFieldAction({
              calendarCustom: {
                ...dateRange,
              },
              event: null,
              sessions: [],
            }),
          );

          setIsCalendarOpen(false);

          dispatch(actions.getLiveEventsAction());
        }}
      />
    </Layout>
  );
}

export default LiveDashboard;
