import { useCallback } from 'react';
import { useNavigate } from 'react-router';

import { debounce } from 'lodash-es';
import {
  IconAdjustmentsCheck,
  IconMathFunction,
  IconRoute,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuSwitcher from '@material-hu/components/design-system/Switcher';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useGoalCyclesConfiguration from 'src/pages/dashboard/Goals/hooks/useGoalCyclesConfiguration';
import { goalRoutes } from 'src/pages/dashboard/Goals/routes';
import { useLokaliseTranslation } from 'src/utils/i18n';

const DEBOUNCE_VALUE = 50;

const GoalConfigurationTab = () => {
  const { t } = useLokaliseTranslation('goals');
  const HuGoThemeProvider = useHuGoTheme();
  const navigate = useNavigate();

  const {
    mathFormulasEnabled,
    goalFlowEnabled,
    bossCanEditPublishedObjectives,
    isLoadingGoalCyclesConfiguration,
    isErrorGoalCyclesConfiguration,
    updateConfigMutation,
  } = useGoalCyclesConfiguration();

  const disabled =
    isLoadingGoalCyclesConfiguration || isErrorGoalCyclesConfiguration;

  const debouncedMathFormulasChange = useCallback(
    debounce((checked: boolean) => {
      updateConfigMutation.mutate({
        mathFormulasEnabled: checked,
        goalFlowEnabled,
        bossCanEditPublishedObjectives,
      });
    }, DEBOUNCE_VALUE),
    [updateConfigMutation, goalFlowEnabled, bossCanEditPublishedObjectives],
  );

  const debouncedFlowSwitchChange = useCallback(
    debounce((checked: boolean) => {
      updateConfigMutation.mutate({
        mathFormulasEnabled,
        goalFlowEnabled: checked,
        bossCanEditPublishedObjectives,
      });
    }, DEBOUNCE_VALUE),
    [updateConfigMutation, mathFormulasEnabled, bossCanEditPublishedObjectives],
  );

  const debouncedLeaderEditionChange = useCallback(
    debounce((checked: boolean) => {
      updateConfigMutation.mutate({
        mathFormulasEnabled,
        goalFlowEnabled,
        bossCanEditPublishedObjectives: checked,
      });
    }, DEBOUNCE_VALUE),
    [updateConfigMutation, mathFormulasEnabled, goalFlowEnabled],
  );

  const handleMathFormulasChange = useCallback(
    (checked: boolean) => {
      if (!disabled) {
        debouncedMathFormulasChange(checked);
      }
    },
    [disabled, debouncedMathFormulasChange],
  );

  const handleFlowSwitchChange = useCallback(
    (checked: boolean) => {
      if (!disabled) {
        debouncedFlowSwitchChange(checked);
      }
    },
    [disabled, debouncedFlowSwitchChange],
  );

  const handleLeaderEditionChange = useCallback(
    (checked: boolean) => {
      if (!disabled) {
        debouncedLeaderEditionChange(checked);
      }
    },
    [disabled, debouncedLeaderEditionChange],
  );

  return (
    <HuGoThemeProvider>
      <Stack
        sx={{
          padding: 3,
          justifyContent: 'center',
          alignItems: 'center',
          width: '40rem',
          margin: '0 auto',
          gap: 3,
        }}
      >
        <HuCardContainer
          hasShadow
          fullWidth
          sx={{ flexDirection: 'row' }}
          padding={24}
          {...(mathFormulasEnabled && {
            footer: {
              action1: {
                onClick: () => navigate(goalRoutes.goalConfiguration()),
                title: t('configuration.go'),
              },
              text: '',
            },
          })}
        >
          <Stack sx={{ flexDirection: 'row', gap: 1 }}>
            <Stack sx={{ flexDirection: 'row', gap: 1 }}>
              <Stack
                sx={{
                  backgroundColor: theme =>
                    theme.palette.hugoBackground?.neutralBgSecondary,
                  borderRadius: '50%',
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: 40,
                  width: 40,
                  flex: 'none',
                }}
              >
                <IconMathFunction />
              </Stack>
            </Stack>
            <Stack sx={{ justifyContent: 'center', alignItems: 'center' }}>
              <HuSwitcher
                title={t('formulas.title')}
                description={t('configuration.description')}
                value={mathFormulasEnabled}
                onChange={handleMathFormulasChange}
                disabled={disabled}
              />
            </Stack>
          </Stack>
        </HuCardContainer>

        <HuCardContainer
          hasShadow
          fullWidth
          sx={{ flexDirection: 'row' }}
          padding={24}
        >
          <Stack sx={{ flexDirection: 'column', gap: 1 }}>
            <Stack sx={{ flexDirection: 'row', gap: 1 }}>
              <Stack sx={{ flexDirection: 'row', gap: 1 }}>
                <Stack
                  sx={{
                    backgroundColor: theme =>
                      theme.palette.hugoBackground?.neutralBgSecondary,
                    borderRadius: '50%',
                    justifyContent: 'center',
                    alignItems: 'center',
                    height: 40,
                    width: 40,
                    flex: 'none',
                  }}
                >
                  <IconRoute />
                </Stack>
              </Stack>
              <Stack sx={{ justifyContent: 'center', alignItems: 'center' }}>
                <HuSwitcher
                  title={t('configuration.approval_flow')}
                  description={t('configuration.approval_flow_description')}
                  value={goalFlowEnabled}
                  onChange={handleFlowSwitchChange}
                  disabled={disabled}
                />
              </Stack>
            </Stack>
            {goalFlowEnabled && (
              <>
                <Divider sx={{ my: 2 }} />
                <Stack sx={{ flexDirection: 'row', gap: 1 }}>
                  <Stack sx={{ flexDirection: 'row', gap: 1 }}>
                    <Stack
                      sx={{
                        backgroundColor: theme =>
                          theme.palette.hugoBackground?.neutralBgSecondary,
                        borderRadius: '50%',
                        justifyContent: 'center',
                        alignItems: 'center',
                        height: 40,
                        width: 40,
                        flex: 'none',
                      }}
                    >
                      <IconAdjustmentsCheck />
                    </Stack>
                  </Stack>
                  <Stack
                    sx={{ justifyContent: 'center', alignItems: 'center' }}
                  >
                    <HuSwitcher
                      title={t('configuration.leader_edition')}
                      description={t(
                        'configuration.leader_edition_description',
                      )}
                      value={bossCanEditPublishedObjectives}
                      onChange={handleLeaderEditionChange}
                      disabled={disabled}
                    />
                  </Stack>
                </Stack>
              </>
            )}
          </Stack>
        </HuCardContainer>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default GoalConfigurationTab;
