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

import { FORM_DOWNLOAD_STATUS_START, TAB_FORM_DETAILS, TAB_FORM_TRIGGER } from '../../constants';
import {
  FORM_SUBMIT_MODE_DUPLICATE,
  FORM_SUBMIT_MODE_UPDATE,
  STATUS_ARCHIVED,
  TARGET_PLACEMENT_TYPE_PLAYER,
  TARGET_PLACEMENT_TYPE_VIDEO,
  TARGET_PLACEMENT_TYPE_WATCH,
  TRIGGER_TIMESTAMP,
} from '../constants';
import { PCN_FORMS_GET_REPORT } from '@/modules/@common/acl/constants';

import * as selectors from '../redux/selectors';
import {
  createFormAction,
  downloadFormDataAction,
  duplicateFormAction,
  getFormByIdAction,
  getTemplateByIdAction,
  setActiveTabIdAction,
  setErrorByPropAction,
  setFieldAction,
  setInitialAction,
  setScrollToFieldNameAction,
  updateFormAction,
  validateFields,
} from '../redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import useFormSubmitMode from '@/modules/forms/helpers/useFormSubmitMode';
import useGetReadOnlyStatus from '@/modules/forms/helpers/useGetReadOnlyStatus';

import { Form, FormContent } from '@/modules/@common/Form';
import DownloadResponse from '@/modules/forms/common/components/DownloadResponse';
import DetailsTab from './DetailsTab/DetailsTab';
import TriggerTab from './TriggerTab/TriggerTab';
import {
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Stack,
  Tab,
  TabContent,
  Tabs,
  Typography,
} from '@/mui/components';

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

function Editor() {
  const store = useStore();
  const dispatch = useDispatch();
  const router = useRouter();
  const [param] = router.query.params;

  const [isDownloadResponseOpen, setDownloadResponseOpen] = useState(false);
  const id = parseInt(param, 10);
  const formSubmitMode = useFormSubmitMode();
  const activeTabId = useSelector(selectors.activeTabIdSelector);
  // const isValidToSave = useSelector(checkIsValidToSaveCalculation);
  const name = useSelector(selectors.nameSelector);
  const status = useSelector(selectors.statusSelector);
  const isFormDownloadInProgress = useSelector(selectors.isFormDownloadInProgressSelector);
  const shouldShowDownloadTryRequestOverConfirm = useSelector(
    selectors.shouldShowDownloadTryRequestOverConfirmSelector,
  );
  const userPermissions = useSelector(getUserPermissionsSelector);

  const readOnly = useGetReadOnlyStatus(status);

  const labels = {
    [FORM_SUBMIT_MODE_UPDATE]: 'Update',
    [FORM_SUBMIT_MODE_DUPLICATE]: 'Duplicate',
    default: 'Save',
  };

  const handleCloseRetryConfirm = () => {
    dispatch(
      setFieldAction({
        shouldShowDownloadTryRequestOverConfirm: false,
      }),
    );
  };

  const handleDownloadForm = (startDate) => {
    dispatch(
      downloadFormDataAction({
        formId: id,
        startDate,
        status: FORM_DOWNLOAD_STATUS_START,
      }),
    );

    setDownloadResponseOpen(false);
  };

  useEffect(() => {
    if (id) {
      dispatch(
        getFormByIdAction({
          id,
          isDuplicate: formSubmitMode === FORM_SUBMIT_MODE_DUPLICATE,
        }),
      );
    } else {
      dispatch(setInitialAction());
    }
  }, [id]);

  useEffect(() => {
    const { templateId } = router.query;

    if (templateId) {
      dispatch(getTemplateByIdAction(+templateId));
    }
  }, []);

  const tabs = [
    {
      title: 'General',
      id: TAB_FORM_DETAILS,
      content: DetailsTab,
    },
    {
      title: 'Trigger',
      id: TAB_FORM_TRIGGER,
      content: TriggerTab,
    },
  ];

  const saveToServerForm = () => {
    const state = store.getState();
    const allProps = selectors.fullAccessToStoreFieldsForValidation(state);

    const { validation, errorList } = validateFields(
      selectors
        .schemeSelector(state)
        .filter(({ tabId }) => tabs.some((tab) => tab.id === tabId))
        .filter(({ fieldName }) => {
          if (['termsConditions.src', 'termsConditions.title'].includes(fieldName)) {
            return allProps.termsConditions.isActive;
          }

          if (fieldName === 'skipButton.title') {
            return allProps.skipButton.isActive;
          }

          if (fieldName === 'trigger.triggerTime') {
            return allProps.status && allProps.trigger.triggerAction === TRIGGER_TIMESTAMP;
          }

          if (fieldName === 'trigger.watch') {
            return allProps.status && allProps.trigger.targetPlacementType === TARGET_PLACEMENT_TYPE_WATCH;
          }

          if (fieldName === 'trigger.playerName') {
            return allProps.status && allProps.trigger.targetPlacementType === TARGET_PLACEMENT_TYPE_PLAYER;
          }

          if (fieldName === 'trigger.video') {
            return allProps.status && allProps.trigger.targetPlacementType === TARGET_PLACEMENT_TYPE_VIDEO;
          }

          return true;
        })
        .map(({ fieldName }) => fieldName),
      allProps,
    );

    if (errorList.length) {
      const errorField = errorList.find((error) => error.tabId === activeTabId) ?? errorList[0];

      dispatch(setActiveTabIdAction(errorField.tabId));
      dispatch(setScrollToFieldNameAction(errorField.fieldName));
    } else if (formSubmitMode === FORM_SUBMIT_MODE_UPDATE) {
      dispatch(updateFormAction());
    } else if (formSubmitMode === FORM_SUBMIT_MODE_DUPLICATE) {
      dispatch(duplicateFormAction());
    } else {
      dispatch(createFormAction());
    }

    dispatch(setErrorByPropAction(validation));
  };

  let pageTitle = 'New Form';
  if (formSubmitMode === FORM_SUBMIT_MODE_DUPLICATE) {
    pageTitle = 'Copy Form';
  } else if (id) {
    pageTitle = `${name} > Settings`;
  }

  return (
    <div className={styles.Wrapper}>
      <Stack direction="column" fullWidth justifyContent="center" className={styles.Title}>
        <Typography component="div" variant="h6" noWrap>
          {pageTitle}
        </Typography>
      </Stack>
      <Stack
        spacing={1}
        fullWidth
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        className={styles.Controls}
      >
        {tabs.length > 1 && (
          <Tabs
            size="medium"
            value={activeTabId}
            className={styles.Tabs}
            onChange={(event, value) => dispatch(setActiveTabIdAction(value))}
          >
            {tabs.map((tab) => (
              <Tab key={tab.id} label={tab.title} value={tab.id} />
            ))}
          </Tabs>
        )}
        <Stack spacing={2} justifyContent="flex-end" alignItems="center" direction="row">
          {hasPermission(PCN_FORMS_GET_REPORT, userPermissions) && (
            <>
              {isFormDownloadInProgress && (
                <Chip
                  icon={<CircularProgress color="success" size="x2Small" />}
                  color="success"
                  label="Processing"
                  variant="text"
                />
              )}
              {!isFormDownloadInProgress && (
                <Button
                  variant="text"
                  size="small"
                  color="neutral"
                  shape="rounded"
                  startIcon={<FileDownloadRounded />}
                  onClick={() => setDownloadResponseOpen(true)}
                  disabled={formSubmitMode !== FORM_SUBMIT_MODE_UPDATE}
                >
                  Download Responses
                </Button>
              )}
              <Divider flexItem orientation="vertical" />
            </>
          )}

          <Button
            size="small"
            variant="outlined"
            onClick={() => {
              dispatch(setInitialAction());
              router.push('/forms');
            }}
          >
            Cancel
          </Button>
          {!readOnly && (
            <Button
              size="small"
              variant="contained"
              color="primary"
              disabled={status === STATUS_ARCHIVED}
              onClick={saveToServerForm}
            >
              {labels[formSubmitMode] ?? labels.default}
            </Button>
          )}
        </Stack>
      </Stack>
      <Form scrollFieldSelector={selectors.scrollFieldSelector}>
        {tabs.map((tab) => {
          const Content = tab.content;

          return (
            <TabContent key={tab.id} component={FormContent} selectedId={activeTabId} id={tab.id}>
              <Content />
            </TabContent>
          );
        })}
      </Form>

      {isDownloadResponseOpen && (
        <DownloadResponse open onDownload={handleDownloadForm} onClose={() => setDownloadResponseOpen(false)} />
      )}
      {shouldShowDownloadTryRequestOverConfirm && (
        <Dialog maxWidth="lg" onClose={handleCloseRetryConfirm}>
          <DialogTitle>The process is taking longer than expected.</DialogTitle>
          <DialogContent>
            <Typography variant="body1" color="text.primary" fontWeight={500}>
              You’ll receive the report to your email when ready.
            </Typography>
            <Typography variant="body1" color="text.primary" fontWeight={400}>
              While this process may take some time, you can continue to work in the AnyClip Platform.
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button size="small" variant="outlined" color="primary" onClick={handleCloseRetryConfirm}>
              Cancel
            </Button>
            <Button size="small" variant="contained" color="primary" onClick={handleCloseRetryConfirm}>
              Got It
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </div>
  );
}

export default Editor;
