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

import { STATUS_ARCHIVED, TYPE_CSV } 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';
import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from '@/mui/components';

function Csv() {
  const store = useStore();
  const dispatch = useAppDispatch();
  const router = useRouter();
  const [shouldShowAutoImportWarning, setShouldShowAutoImportWarning] = React.useState(false);

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

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

  const tabs = [
    {
      title: 'General',
      id: TAB_GENERAL,
      content: GeneralTab,
      show: true,
    },
    {
      title: 'Advanced',
      id: TAB_ADVANCED,
      content: AdvancedTab,
      show: true,
    },
    {
      title: 'Models',
      id: TAB_MODEL,
      content: ModelTab,
      show: true,
    },
    {
      title: 'Automation Script',
      id: TAB_SCRIPT,
      content: ScriptTab,
      show: true,
    },
  ].filter((tab) => tab.show);

  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 {
      if (!isAutoImport) {
        setShouldShowAutoImportWarning(true);
        return;
      }

      handleSubmitForm();
    }

    dispatch(setErrorByPropAction(validation));
  };

  const handleCloseImportWarning = () => setShouldShowAutoImportWarning(false);
  const handleApplyImportWarning = () => {
    handleSubmitForm();
    handleCloseImportWarning();
  };

  return (
    <>
      <FormWrapper
        type={TYPE_CSV}
        sourceTitle="Csv"
        tabs={tabs}
        disabled={status === STATUS_ARCHIVED}
        saveToServerForm={saveToServerForm}
      />

      {shouldShowAutoImportWarning && (
        <Dialog open={!!shouldShowAutoImportWarning} onClose={handleCloseImportWarning} maxWidth="lg">
          <DialogTitle onClose={handleCloseImportWarning}>Disable automated import?</DialogTitle>
          <DialogContent>
            Selecting this option means your videos will not be imported. Would you like to continue?
          </DialogContent>
          <DialogActions>
            <Button variant="outlined" color="primary" size="small" onClick={handleCloseImportWarning}>
              Cancel
            </Button>
            <Button variant="contained" color="primary" size="small" onClick={handleApplyImportWarning}>
              Continue
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

export default Csv;
