import { FC, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useForm, FormProvider } from 'react-hook-form';
import { useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { formatISO } from 'date-fns';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Divider from '@material-hu/mui/Divider';
import TableContainer from '@material-hu/mui/TableContainer';

import ModuleHeader from 'src/pages/dashboard/recognitions/components/ModuleHeader';
import TransactionsSearch from 'src/pages/dashboard/recognitions/components/TransactionsSearch';
import TransactionTable from 'src/pages/dashboard/recognitions/components/TransactionTable';
import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import { recognitionsKeys } from 'src/pages/dashboard/recognitions/queries';
import { recognitionsRoutes } from 'src/pages/dashboard/recognitions/routes';
import { getEmployeeTransactions } from 'src/services/recognitions';
import {
  getFilteredTransactions,
  parseDate,
  getUserId,
} from 'src/utils/recognitions';

import GoBackButton from 'src/components/dashboard/GoBackButton';

const DEFAULT_START_DATE = '2010-06-18T18:00:00';
const DEFAULT_END_DATE = formatISO(new Date());
const DEFAULT_MOVEMENT = 'All';

const Transactions: FC = () => {
  const { t } = useTranslation();
  const userId = getUserId();
  const navigate = useNavigate();

  const [transactions, setTransactions] = useState(null);

  const methods = useForm({
    defaultValues: {
      startDate: DEFAULT_START_DATE,
      endDate: DEFAULT_END_DATE,
      movement: DEFAULT_MOVEMENT,
    },
  });

  const startDate = parseDate(methods.watch('startDate'));
  const endDate = parseDate(methods.watch('endDate'));
  const movement = methods.watch('movement');

  const { isLoading, refetch } = useQuery(
    [recognitionsKeys.ideas(userId)],
    () => getEmployeeTransactions(userId, startDate, endDate),
    {
      enabled: !!userId,
      onSuccess: data => {
        const filteredTrasactions = getFilteredTransactions(data, movement);
        setTransactions(filteredTrasactions);
      },
    },
  );

  const onSubmit = async () => {
    await refetch();
  };

  const handleGoBack = () => navigate(recognitionsRoutes.home());

  if (!userId) {
    navigate(recognitionsRoutes.home());
  }

  return (
    <Box
      sx={{
        backgroundColor: 'background.default',
        minHeight: '100%',
        pt: 3,
        pb: 3,
      }}
    >
      <Container maxWidth="md">
        <GoBackButton onClick={handleGoBack} />
        <Box sx={{ mt: 3, mb: 3 }}>
          <Box
            sx={{
              p: 3,
              width: '100%',
              backgroundColor: '#ffffff',
              borderRadius: '10px',
            }}
          >
            <Helmet>
              <title>{t('RECOGNITIONS')}</title>
            </Helmet>
            <>
              <ModuleHeader title={t('MY_TRANSACTIONS')} />
              <Divider sx={{ borderBottomWidth: 'medium', mt: 2, mb: 3 }} />
              {isLoading && (
                <Box sx={{ textAlign: 'center' }}>
                  <CircularProgress />
                </Box>
              )}
              {!isLoading && (
                <Box>
                  <Box
                    sx={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      my: 4,
                    }}
                  >
                    <FormProvider {...methods}>
                      <TransactionsSearch onSubmit={onSubmit} />
                    </FormProvider>
                  </Box>
                  <TableContainer>
                    <TransactionTable transactions={transactions} />
                  </TableContainer>
                </Box>
              )}
            </>
          </Box>
        </Box>
      </Container>
    </Box>
  );
};

export default Transactions;
