import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import classNames from 'clsx';
import { useRouter } from 'next/router';
import { UploadFile } from '@mui/icons-material';

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

import Empty from '@/modules/@common/Empty/Empty';
import { Layout } from '@/modules/analytics/common/components';
import CancelDialog from './components/CancelDialog';
import EmptyDialog from './components/EmptyDialog';
import Filters from './components/Filters';
import Name from './components/Name';
import Preview from './components/Preview';
import ScheduleDialog from './components/ScheduleDialog';
import SideBar from './components/SideBar';
import { Button, Divider, Stack, Typography } from '@/mui/components';

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

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

  const name = useSelector(selectors.nameSelector);
  const scheduleType = useSelector(selectors.scheduleTypeSelector);
  const scheduleDay = useSelector(selectors.scheduleDaySelector);
  const scheduleTime = useSelector(selectors.scheduleTimeSelector);
  const recipients = useSelector(selectors.recipientsSelector);
  const checkedMetrics = useSelector(selectors.checkedMetricsSelector);
  const checkedDimensions = useSelector(selectors.checkedDimensionsSelector);
  const isReadOnly = useSelector(selectors.isReadOnlySelector);
  const isDownloading = useSelector(selectors.isDownloadingSelector);
  const isLoading = useSelector(selectors.isLoadingSelector);

  const setField = (o) => dispatch(actions.setFieldAction(o));

  const [isScheduleDialogOpen, setIsScheduleDialogOpen] = useState(false);
  const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);
  const [isEmptyDialogOpen, setIsEmptyDialogOpen] = useState(false);
  const router = useRouter();
  const [id] = router.query.params;
  const isCreateForm = id === 'new';
  const isDuplicate = router.query.duplicate;

  const clearForm = () => {
    dispatch(actions.setDefaultSetupPageAction());
  };

  useEffect(() => {
    clearForm();
    if (!isCreateForm) {
      dispatch(actions.getCustomReportByIdAction({ id: +id, isDuplicate }));
    }

    return () => {
      clearForm();
    };
  }, [isDuplicate]);

  const handleChangeName = (newName) => {
    dispatch(
      actions.setFieldAction({
        name: newName,
      }),
    );
  };

  const handleSubmit = () => {
    if (!checkedMetrics?.length) {
      setIsEmptyDialogOpen(true);
      return;
    }

    if (isCreateForm || isDuplicate) {
      dispatch(actions.createCustomReportAction());
    } else {
      dispatch(actions.updateCustomReportAction({ id: +id }));
    }
  };

  const isNotEmpty = !!checkedMetrics?.length || !!checkedDimensions?.length;

  const downloadButtonText = isDownloading ? 'Downloading...' : 'Download';

  return (
    <Layout contentClassName={styles.Layout}>
      <div className={styles.Header}>
        <Name name={name} onChange={handleChangeName} isReadOnly={isReadOnly} />
        <Stack direction="row" alignItems="center" spacing={2}>
          <Button
            data-id="schedule-btn"
            size="small"
            color="neutral"
            variant="text"
            onClick={() => {
              setIsScheduleDialogOpen(true);
            }}
            disabled={isCreateForm || isReadOnly}
          >
            Schedule
          </Button>

          <Button
            data-id="download-btn"
            size="small"
            color="neutral"
            variant="text"
            onClick={() => {
              if (isReadOnly) {
                router.push(`/custom-reports-new/${id}?duplicate=true`);
              } else {
                dispatch(
                  actions.runDownloadReportAction({
                    id: +id,
                    name,
                  }),
                );
              }
            }}
            disabled={isCreateForm || isDownloading}
          >
            {isReadOnly ? 'Duplicate' : downloadButtonText}
          </Button>
          <Divider flexItem orientation="vertical" />
          <Button
            color="primary"
            variant="outlined"
            size="small"
            onClick={() => {
              setIsCancelDialogOpen(true);
            }}
          >
            Cancel
          </Button>
          <Button data-id="save-btn" size="small" onClick={handleSubmit} disabled={isLoading || isReadOnly}>
            Save
          </Button>
        </Stack>
      </div>

      <div className={styles.Main}>
        <SideBar />
        <div className={styles.Info}>
          <Filters />
          <div
            className={classNames(styles.PreviewWrap, {
              [styles.PreviewWrap___empty]: !isNotEmpty,
            })}
          >
            {isNotEmpty ? (
              <Preview checkedMetrics={checkedMetrics} checkedDimensions={checkedDimensions} />
            ) : (
              <Empty icon={<UploadFile fontSize="x4Large" htmlColor="text.disabled" />}>
                <>
                  <Typography variant="h6" color="text.primary" fontWeight={500}>
                    Build your report
                  </Typography>
                  <Typography variant="body1" color="text.secondary" fontWeight={400}>
                    Use the panel on the left to manage report metrics and split them by dimensions
                  </Typography>
                </>
              </Empty>
            )}
          </div>
        </div>
      </div>

      <ScheduleDialog
        open={isScheduleDialogOpen}
        onClose={() => {
          setIsScheduleDialogOpen(false);
        }}
        onSubmit={() => {
          setIsScheduleDialogOpen(false);
          handleSubmit();
        }}
        name={name}
        scheduleType={scheduleType}
        scheduleDay={scheduleDay}
        scheduleTime={scheduleTime}
        recipients={recipients}
        setField={setField}
      />

      <CancelDialog
        open={isCancelDialogOpen}
        onClose={() => {
          setIsCancelDialogOpen(false);
        }}
        onSubmit={() => {
          setIsCancelDialogOpen(false);
          router.push('/custom-reports-new');
        }}
      />

      <EmptyDialog
        open={isEmptyDialogOpen}
        onClose={() => {
          setIsEmptyDialogOpen(false);
        }}
        onSubmit={() => {
          setIsEmptyDialogOpen(false);
        }}
      />
    </Layout>
  );
}

export default ReportSetup;
