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

import {
  FORM_PREVIEW_WIDGET_ID,
  FORM_SUBMIT_MODE_DUPLICATE,
  FORM_SUBMIT_MODE_UPDATE,
  TAB_FORM_DETAILS,
} from '../../constants';
import { PUT_FORM_TEMPLATES } from '@/modules/@common/acl/constants';

import * as selectors from '../redux/selectors';
import {
  getTemplateByIdAction,
  saveProcessAction,
  setActiveTabIdAction,
  setErrorByPropAction,
  setInitialAction,
  setScrollToFieldNameAction,
  validateFields,
} from '../redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserAccountIdSelector, getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import useFormSubmitMode from '@/modules/forms/helpers/useFormSubmitMode';

import { Form, FormContent } from '@/modules/@common/Form';
import DetailsTab from './DetailsTab/DetailsTab';
import { Button, Stack, TabContent, Typography } from '@/mui/components';

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

function Editor() {
  const router = useRouter();
  const store = useStore();
  const [param] = router.query.params;
  const id = parseInt(param, 10);

  const activeTabId = useSelector(selectors.activeTabIdSelector);
  const formSubmitMode = useFormSubmitMode();
  const dispatch = useDispatch();
  const userPermissions = useSelector(getUserPermissionsSelector);
  const name = useSelector(selectors.nameSelector);
  const userAccountId = useSelector(getUserAccountIdSelector);
  const isReadOnlyMode = !hasPermission(PUT_FORM_TEMPLATES, userPermissions);

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

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

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

          if (fieldName === 'account') {
            return !userAccountId;
          }

          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 {
      const $el = document.getElementById(FORM_PREVIEW_WIDGET_ID);
      const $iframe = $el.querySelector('iframe');
      const { body } = $iframe.contentWindow.document;

      const iframeWidth = $iframe.contentWindow.innerWidth;
      const iframeHeight = $iframe.contentWindow.innerHeight;

      const MAX_WIDTH = 113;

      const ratio = MAX_WIDTH / iframeWidth;

      const { toCanvas } = await import('html-to-image');
      const canvas = await toCanvas(body, {
        width: iframeWidth,
        height: iframeHeight,
      });

      const scaledCanvas = document.createElement('canvas');
      scaledCanvas.width = iframeWidth * ratio;
      scaledCanvas.height = iframeHeight * ratio;

      const ctx = scaledCanvas.getContext('2d');
      ctx.drawImage(canvas, 0, 0, iframeWidth, iframeHeight, 0, 0, scaledCanvas.width, scaledCanvas.height);

      dispatch(
        saveProcessAction({
          thumbFile: scaledCanvas.toDataURL('image/png'),
          formSubmitMode,
        }),
      );
    }

    dispatch(setErrorByPropAction(validation));
  };

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

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

  let pageTitle = 'New Form Template';
  if (formSubmitMode === FORM_SUBMIT_MODE_DUPLICATE) {
    pageTitle = 'Copy Form Template';
  } 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}
      >
        <Stack spacing={2} justifyContent="flex-end" alignItems="center" direction="row">
          <Button
            size="small"
            variant="outlined"
            onClick={() => {
              dispatch(setInitialAction());
              router.push('/form-templates');
            }}
          >
            Cancel
          </Button>
          {!isReadOnlyMode && (
            <Button size="small" variant="contained" color="primary" onClick={saveToServerForm}>
              {labels[formSubmitMode] ?? labels.default}
            </Button>
          )}
        </Stack>
      </Stack>
      <Form scrollFieldSelector={selectors.scrollFieldSelector}>
        <TabContent selectedId={activeTabId} id={TAB_FORM_DETAILS} component={FormContent}>
          <DetailsTab />
        </TabContent>
      </Form>
    </div>
  );
}

export default Editor;
