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

import {
  CLEAN_RULE_TYPE_CUSTOM,
  CLEAN_RULE_TYPE_REGEXP,
  TAB_ADVANCED,
  TAB_GENERAL,
  TAB_MARKETPLACE_SELF_SERVICE,
  TAB_PLAYER_SELF_SERVICE,
  TAB_SYNDICATED_CONTENT,
} from '../constants';

import { getCanReadOnly, getHasAccount } from '../helpers/getRestrictions';
import * as selectors from '../redux/selectors';
import {
  createItemAction,
  getItemAction,
  setAction,
  setActiveTabIdAction,
  setErrorByPropAction,
  setScrollToFieldNameAction,
  updateItemAction,
  validateFields,
} from '../redux/slices';
import {
  getUserAccountIdSelector,
  getUserAccountSelector,
  getUserPermissionsSelector,
  getUserRoleTypeSelector,
} from '@/modules/@common/user/redux/selectors';

import { Form, FormContent, FormSection } from '@/modules/@common/Form';
import AdvancedTab from './Tabs/AdvancedTab/AdvancedTab';
import GeneralTab from './Tabs/GeneralTab/GeneralTab';
import MarketplaceSelfServiceTab from './Tabs/MarketplaceSelfServiceTab/MarketplaceSelfServiceTab';
import PlayerSelfServiceTab from './Tabs/PlayerSelfServiceTab/PlayerSelfServiceTab';
import SyndicatedContentTab from './Tabs/SyndicatedContentTab/SyndicatedContentTab';
import { Button, 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 name = useSelector(selectors.nameSelector);
  const activeTabId = useSelector(selectors.activeTabIdSelector);

  const userAccount = useSelector(getUserAccountSelector);
  const userAccountId = useSelector(getUserAccountIdSelector);
  const userRoleType = useSelector(getUserRoleTypeSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);

  const id = parseInt(router.query.id, 10);

  const hasAccount = getHasAccount(userRoleType);
  const canReadOnly = getCanReadOnly(id, userPermissions);

  useEffect(() => {
    if (id) {
      dispatch(getItemAction({ id }));
    }
  }, [id]);

  useEffect(() => {
    if (hasAccount) {
      dispatch(
        setAction({
          account: {
            value: userAccountId,
            label: userAccount?.name,
          },
        }),
      );
    }
  }, [hasAccount]);

  const tabs = [
    {
      title: 'General',
      id: TAB_GENERAL,
      content: GeneralTab,
    },
    !hasAccount && {
      title: 'Syndicated Content',
      id: TAB_SYNDICATED_CONTENT,
      content: SyndicatedContentTab,
    },
    !hasAccount && {
      title: 'Player Self-Service',
      id: TAB_PLAYER_SELF_SERVICE,
      content: PlayerSelfServiceTab,
    },
    !hasAccount && {
      title: 'Marketplace Self-Service',
      id: TAB_MARKETPLACE_SELF_SERVICE,
      content: MarketplaceSelfServiceTab,
    },
    !hasAccount && {
      title: 'Advanced',
      id: TAB_ADVANCED,
      content: AdvancedTab,
    },
  ].filter(Boolean);

  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 (fieldName === 'demandAccount') {
            return allProps.mpSelfService;
          }

          if (fieldName === 'defaultRule.cleanUrlRuleValue') {
            return [CLEAN_RULE_TYPE_CUSTOM, CLEAN_RULE_TYPE_REGEXP].includes(allProps.defaultRule.cleanUrlRuleType);
          }

          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 (id) {
      dispatch(updateItemAction(id));
    } else {
      dispatch(createItemAction());
    }

    dispatch(setErrorByPropAction(validation));
  };

  return (
    <div className={styles.Wrapper}>
      <Stack direction="column" fullWidth justifyContent="center" className={styles.Title}>
        <Typography component="div" variant="h6" noWrap>
          {id ? `${name} > Settings` : 'New Hub'}
        </Typography>
      </Stack>
      <Stack
        spacing={1}
        fullWidth
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        className={styles.Controls}
      >
        {tabs.length > 1 && (
          <Tabs
            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">
          <Button variant="outlined" size="small" color="primary" shape="rounded" onClick={() => router.push('/hubs')}>
            Cancel
          </Button>
          {!canReadOnly && (
            <Button variant="contained" size="small" color="primary" shape="rounded" onClick={saveToServerForm}>
              Save
            </Button>
          )}
        </Stack>
      </Stack>
      <Form scrollFieldSelector={selectors.scrollFieldSelector}>
        <FormContent>
          {tabs.map((tab) => {
            const Content = tab.content;

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

export default Editor;
