import React, { useEffect } from 'react';
import { useRouter } from 'next/router';

import { FeedType } from '@/modules/feeds/types';

import * as selectors from '@/modules/feeds/Editor/redux/selectors';
import {
  getMetadataAction,
  setAction,
  setActiveTabIdAction,
  setInitialAction,
} from '@/modules/feeds/Editor/redux/slices';

import { Form, FormContent, FormSection } from '@/modules/@common/Form';
import { useAppDispatch, useAppSelector } from '@/modules/@common/store/hooks';
import useSetStoreDefaultValues from '@/modules/feeds/Editor/hooks/useSetStoreDefaultValues';
import { Button, Stack, Tab, TabContent, Tabs, Typography } from '@/mui/components';

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

type FormWrapperPropsType = {
  type: FeedType;
  sourceTitle: string;
  tabs: {
    title: string;
    id: string;
    content: React.FC;
  }[];
  disabled?: boolean;
  saveToServerForm: () => void;
};

// @todo Remove after move from js to ts FormSection
const FormSectionTyped: React.ForwardRefExoticComponent<React.PropsWithoutRef<object> & React.RefAttributes<unknown>> =
  FormSection;

function FormWrapper({ type, sourceTitle, tabs, saveToServerForm, disabled = false }: FormWrapperPropsType) {
  useSetStoreDefaultValues(type);

  const dispatch = useAppDispatch();
  const router = useRouter();

  const activeTabId = useAppSelector(selectors.activeTabIdSelector);
  const name = useAppSelector(selectors.nameSelector);
  const displayName = useAppSelector(selectors.descriptionSelector);

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

  useEffect(() => {
    dispatch(getMetadataAction({ id }));
    dispatch(setAction({ type }));

    return () => {
      dispatch(setInitialAction());
    };
  }, [id]);

  return (
    <div className={styles.Wrapper}>
      <Stack direction="column" fullWidth justifyContent="center" className={styles.Title}>
        <Typography component="div" variant="h6" noWrap>
          {id ? `Source ${sourceTitle} > ${name || displayName} > Settings` : `New ${sourceTitle}`}
        </Typography>
      </Stack>
      <Stack
        spacing={1}
        fullWidth
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        className={styles.Controls}
      >
        {tabs.length > 1 && (
          <Tabs
            size="medium"
            orientation="horizontal"
            value={activeTabId}
            className={styles.Tabs}
            onChange={(event: unknown, value: string) => 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('/feeds')}>
            Cancel
          </Button>
          <Button
            variant="contained"
            size="small"
            color="primary"
            shape="rounded"
            onClick={saveToServerForm}
            disabled={disabled}
          >
            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}>
                <FormSectionTyped>
                  <Content />
                </FormSectionTyped>
              </TabContent>
            );
          })}
        </FormContent>
      </Form>
    </div>
  );
}

export default FormWrapper;
