import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector, useStore } from 'react-redux';
import { useRouter } from 'next/router';
import { DeleteOutlined } from '@mui/icons-material';

import { TAB_CONTENT, TAB_DASHBOARDS, TAB_DETAILS, TAB_FEATURES } from '../constants';
import { ACCOUNT_BULK_DELETE_VIDEOS } from '@/modules/@common/acl/constants';
import { ACCOUNT_TYPE_PUBLISHER } from '@/modules/accounts/List/constants';

import * as selectors from '../redux/selectors';
import {
  createItemAction,
  deleteAllVideos,
  getDataAction as getContentOwnersDataAction,
  getItemAction,
  setActiveTabIdAction,
  setErrorByPropAction,
  setInitialAction,
  setScrollToFieldNameAction,
  updateItemAction,
  validateFields,
} from '../redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

import { Form, FormContent, FormSection } from '@/modules/@common/Form';
import ContentTab from './Tabs/ContentTab/ContentTab';
import DashboardsTab from './Tabs/DashboardsTab/DashboardsTab';
import DetailsTab from './Tabs/DetailsTab/DetailsTab';
import FeaturesTab from './Tabs/FeaturesTab/FeaturesTab';
import {
  Button,
  Checkbox,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Stack,
  Tab,
  TabContent,
  Tabs,
  Typography,
} from '@/mui/components';

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

function Editor() {
  const dispatch = useDispatch();
  const router = useRouter();
  const store = useStore();

  const [isShowDeleteVideoConfirm, setIsShowDeleteVideoConfirm] = useState(false);
  const [isConfirmDeleteVideo, setIsConfirmDeleteVideo] = useState(false);

  const userPermissions = useSelector(getUserPermissionsSelector);

  const activeTabId = useSelector(selectors.activeTabIdSelector);
  const featuresUi = useSelector(selectors.featuresUiSelector);
  const dashboardGeneral = useSelector(selectors.dashboardsGeneralSelector);
  const dashboardCustom = useSelector(selectors.dashboardsCustomSelector);
  const name = useSelector(selectors.nameSelector);
  const type = useSelector(selectors.typeSelector);

  const { id } = router.query;

  const canDeleteAllVideos = hasPermission(ACCOUNT_BULK_DELETE_VIDEOS, userPermissions) && id !== 'new';

  const tabs = [
    {
      title: 'General',
      id: TAB_DETAILS,
      content: DetailsTab,
    },
    {
      title: 'Features',
      id: TAB_FEATURES,
      content: FeaturesTab,
      disabled: !featuresUi?.length,
    },
    {
      title: 'Dashboards',
      id: TAB_DASHBOARDS,
      content: DashboardsTab,
      disabled: !(dashboardGeneral?.length || dashboardCustom?.length),
    },
    {
      title: 'Content',
      id: TAB_CONTENT,
      content: ContentTab,
      disabled: id === 'new',
    },
  ];

  const handleCloseDeleteConfirm = () => {
    setIsShowDeleteVideoConfirm(false);
    setIsConfirmDeleteVideo(false);
  };

  const handleDeleteAllVideo = () => {
    dispatch(deleteAllVideos(id));
    handleCloseDeleteConfirm();
  };

  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 (type !== ACCOUNT_TYPE_PUBLISHER) {
            return !['publisherRevShare', 'expenses'].includes(fieldName);
          }

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

    dispatch(setErrorByPropAction(validation));
  };

  useEffect(() => {
    dispatch(setInitialAction());
    dispatch(getItemAction(id));
    if (id !== 'new') {
      dispatch(getContentOwnersDataAction(id));
    }
  }, [id]);

  useEffect(() => () => dispatch(setInitialAction()), []);

  return (
    <div className={styles.Wrapper}>
      <Stack direction="column" fullWidth justifyContent="center" className={styles.Title}>
        <Typography component="div" variant="h6" noWrap>
          {id === 'new' ? 'New Account' : `${name} > Settings`}
        </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, value) => dispatch(setActiveTabIdAction(value))}
          >
            {tabs.map((tab) => (
              <Tab key={tab.id} label={tab.title} value={tab.id} disabled={tab.disabled} />
            ))}
          </Tabs>
        )}
        <Stack spacing={2} justifyContent="flex-end" alignItems="center" direction="row">
          {canDeleteAllVideos && (
            <>
              <Button
                size="small"
                color="neutral"
                variant="text"
                startIcon={<DeleteOutlined />}
                onClick={() => setIsShowDeleteVideoConfirm(true)}
              >
                Delete All Videos
              </Button>
              <Divider flexItem orientation="vertical" />
            </>
          )}
          <Button
            variant="outlined"
            size="small"
            color="primary"
            shape="rounded"
            onClick={() => router.push('/accounts')}
          >
            Cancel
          </Button>
          <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}>
                {tab.id !== TAB_CONTENT && (
                  <FormSection>
                    <Content />
                  </FormSection>
                )}
                {tab.id === TAB_CONTENT && <Content />}
              </TabContent>
            );
          })}
        </FormContent>
      </Form>

      {isShowDeleteVideoConfirm && (
        <Dialog open={isShowDeleteVideoConfirm} onClose={handleCloseDeleteConfirm} maxWidth="md">
          <DialogTitle onClose={handleCloseDeleteConfirm}>Video Delete Confirmation</DialogTitle>
          <DialogContent>
            <Stack gap={1}>
              <Typography component="p" variant="body2">
                Are you sure you want to delete all videos for <b>{name}</b> account?
              </Typography>
              <Typography component="p" variant="body2">
                This action will delete all video files for this account and cannot be undone.
              </Typography>
            </Stack>
          </DialogContent>
          <DialogActions>
            <Stack fullWidth direction="row" justifyContent="space-between" alignItems="center">
              <Stack direction="row" gap={2} alignItems="center">
                <Typography component="p" variant="body2">
                  Confirm
                </Typography>
                <Checkbox
                  checked={isConfirmDeleteVideo}
                  onChange={() => setIsConfirmDeleteVideo(!isConfirmDeleteVideo)}
                />
              </Stack>
              <Stack direction="row" alignItems="center" gap={2}>
                <Button variant="outlined" color="primary" onClick={handleCloseDeleteConfirm}>
                  Cancel
                </Button>
                <Button
                  variant="contained"
                  color="error"
                  disabled={!isConfirmDeleteVideo}
                  onClick={handleDeleteAllVideo}
                >
                  Delete All Videos
                </Button>
              </Stack>
            </Stack>
          </DialogActions>
        </Dialog>
      )}
    </div>
  );
}

export default Editor;
