import { FormProvider, useForm } from 'react-hook-form';
import { useLocation } from 'react-router';

import Card from '@material-hu/mui/Card';
import Stack from '@material-hu/mui/Stack';

import { AnalyticsTypes } from 'src/types/insights';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { createDistantDate, getEndOfDay } from 'src/utils/timeUtils';

import FormDatePicker from 'src/components/FormInputs/FormDatePicker';

import AnalyticsGeneral from './components/General';
import AnalyticsTopics from './components/Topics';

const ALL_MODULES = 'ALL';
const MODULES_MAP = {
  [ALL_MODULES]: AnalyticsGeneral,
  [AnalyticsTypes.TICKETS]: AnalyticsTopics,
};

const GenericInsights = () => {
  const { t } = useLokaliseTranslation('insights');
  const location = useLocation() as { state: { type: AnalyticsTypes } };

  const form = useForm({
    defaultValues: {
      minDate: createDistantDate({ weeks: -1 }),
      maxDate: getEndOfDay(new Date()),
      currentModule: location?.state?.type || ALL_MODULES,
      pagination: {
        page: 0,
        limit: 10,
      },
    },
  });
  const { watch } = form;
  const { currentModule, minDate, maxDate } = watch();

  const CurrentModuleComponent =
    MODULES_MAP[currentModule as keyof typeof MODULES_MAP] ?? null;

  return (
    <Stack>
      <FormProvider {...form}>
        <Card
          variant="outlined"
          sx={{ alignSelf: 'end', mb: 3, width: 'fit-content' }}
        >
          <Stack sx={{ flexDirection: 'row', p: 2, gap: 2 }}>
            <FormDatePicker
              name="minDate"
              textFieldProps={{ size: 'small', label: t('GENERIC_TAB.FROM') }}
              datePickerProps={{ disableFuture: true, maxDate }}
            />
            <FormDatePicker
              name="maxDate"
              textFieldProps={{ size: 'small', label: t('GENERIC_TAB.TO') }}
              datePickerProps={{ disableFuture: true, minDate }}
              isStart={false}
            />
          </Stack>
        </Card>
        {CurrentModuleComponent && <CurrentModuleComponent />}
      </FormProvider>
    </Stack>
  );
};

export default GenericInsights;
