import React from 'react';
import { useStore } from 'react-redux';
import { useRouter } from 'next/router';

import { STATUS_ARCHIVED, TYPE_MANUAL } from '@/modules/feeds/constants';
import { TAB_ADVANCED, TAB_GENERAL, TAB_MODEL, TAB_SCRIPT } from '@/modules/feeds/Editor/constants';

import * as selectors from '@/modules/feeds/Editor/redux/selectors';
import {
  createItemAction,
  setActiveTabIdAction,
  setErrorByPropAction,
  setScrollToFieldNameAction,
  updateItemAction,
  validateFields,
} from '@/modules/feeds/Editor/redux/slices';

import { useAppDispatch, useAppSelector } from '@/modules/@common/store/hooks';
import FormWrapper from '@/modules/feeds/Editor/components/FormWrapper/FormWrapper';
import ModelTab from '../../FormTabs/ModelTab/ModelTab';
import ScriptTab from '../../FormTabs/ScriptTab/ScriptTab';
import AdvancedTab from './Tabs/AdvancedTab/AdvancedTab';
import GeneralTab from './Tabs/GeneralTab/GeneralTab';

function Manual() {
  const store = useStore();
  const dispatch = useAppDispatch();
  const router = useRouter();

  const activeTabId = useAppSelector(selectors.activeTabIdSelector);
  const status = useAppSelector(selectors.statusSelector);

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

  const tabs = [
    {
      title: 'General',
      id: TAB_GENERAL,
      content: GeneralTab,
    },
    {
      title: 'Advanced',
      id: TAB_ADVANCED,
      content: AdvancedTab,
    },
    {
      title: 'Models',
      id: TAB_MODEL,
      content: ModelTab,
    },
    {
      title: 'Automation Script',
      id: TAB_SCRIPT,
      content: ScriptTab,
    },
  ];

  const handleSubmitForm = () => {
    if (id) {
      dispatch(updateItemAction({ id }));
    } else {
      dispatch(createItemAction());
    }
  };

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

    const { validation, errorList } = validateFields(
      selectors
        .schemeSelector(state)
        .filter(({ tabId }: { tabId: string }) => tabs.some((tab) => tab.id === tabId))
        .map(({ fieldName }: { fieldName: string }) => fieldName),
      allProps,
    );

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

      dispatch(setActiveTabIdAction(errorField.tabId));
      dispatch(setScrollToFieldNameAction(errorField.fieldName));
    } else {
      handleSubmitForm();
    }

    dispatch(setErrorByPropAction(validation));
  };

  return (
    <FormWrapper
      type={TYPE_MANUAL}
      sourceTitle="Manual"
      tabs={tabs}
      disabled={status === STATUS_ARCHIVED}
      saveToServerForm={saveToServerForm}
    />
  );
}

export default Manual;
