import { useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useMutation } from 'react-query';
import { useNavigate, useLocation, Location } from 'react-router';

import { IconTargetArrow, IconPlus } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { colorPalette } from '@material-hu/theme/hugo/colors';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuTabs from '@material-hu/components/design-system/Tabs';

import {
  capabilityToi18nKey,
  useCustomServerTranslation,
} from 'src/hooks/useCustomServerTranslation';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import GoalConfigurationTab from 'src/pages/dashboard/Goals/Configuration/components/GoalConfigurationTab';
import { GoalCycleTab } from 'src/pages/dashboard/Goals/constants';
import { createCycle } from 'src/services/goalsService';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import { goalRoutes } from '../routes';

import CyclesTable from './components/CyclesTable';

const TAB_COMPONENTS = {
  [GoalCycleTab.TABLE]: CyclesTable,
  [GoalCycleTab.CONFIG]: GoalConfigurationTab,
} as const;

const getInitialTab = (location: Location): GoalCycleTab => {
  return location.state?.activeTab === GoalCycleTab.CONFIG
    ? GoalCycleTab.CONFIG
    : GoalCycleTab.TABLE;
};

const GoalCycles = () => {
  const { t } = useLokaliseTranslation('performance');
  const navigate = useNavigate();
  const location = useLocation();
  const HuGoThemeProvider = useHuGoTheme();

  const getCustomTitle = useCustomServerTranslation();

  const createCycleMutation = useMutation(
    () => createCycle(`${t('cycles.new_cycle_short')}`),
    {
      onSuccess: ({ data }) => {
        navigate(goalRoutes.newCycle(data.id));
      },
    },
  );

  const title = getCustomTitle(
    capabilityToi18nKey(UserPermissions.VIEW_GOALS),
    'TITLE_' + UserPermissions.VIEW_GOALS,
  );

  const initialTab = getInitialTab(location);
  const [selectedTab, setSelectedTab] = useState(initialTab);

  const goalTabs = [
    { label: t('general:cycles'), value: GoalCycleTab.TABLE },
    { label: t('general:settings'), value: GoalCycleTab.CONFIG },
  ];

  const SelectedComponent = TAB_COMPONENTS[selectedTab];

  const handleTabChange = (value: GoalCycleTab) => {
    setSelectedTab(value);
  };

  return (
    <HuGoThemeProvider>
      <Stack
        direction="column"
        sx={{ height: '100%' }}
      >
        <Helmet>
          <title>{formatTitle(title)}</title>
        </Helmet>
        <Stack
          sx={{
            backgroundColor: colorPalette.hugoBackground.neutralBg,
            flex: 1,
            py: 3,
            px: 3,
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
              mb: 3,
            }}
          >
            <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
              <Stack
                sx={{
                  borderRadius: '50%',
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: 40,
                  width: 40,
                  backgroundColor: colorPalette.hugoBackground.primaryBgLighter,
                  color: colorPalette.textColors.primaryText,
                }}
              >
                <IconTargetArrow />
              </Stack>
              <Typography
                variant="globalL"
                fontWeight="fontWeightSemiBold"
              >
                {title}
              </Typography>
            </Stack>
            <Button
              variant="contained"
              onClick={() => createCycleMutation.mutateAsync()}
              startIcon={<IconPlus size={16} />}
            >
              {t('cycles.new_cycle_short')}
            </Button>
          </Stack>
          <HuTabs
            tabs={goalTabs}
            value={selectedTab}
            defaultValue={GoalCycleTab.TABLE}
            onTabChange={value => handleTabChange(value as GoalCycleTab)}
          />
          <SelectedComponent />
        </Stack>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default GoalCycles;
