import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { useQuery } from 'react-query';
import { useLocation } from 'react-router-dom';

import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import Stack from '@material-hu/mui/Stack';

import HuPagination from '@material-hu/components/design-system/Inputs/Pagination';
import HuSearch from '@material-hu/components/design-system/Inputs/Search';

import CycleSelector from 'src/pages/dashboard/goals/components/CycleSelector';
import { MY_TEAM_PAGE_SIZE } from 'src/pages/dashboard/goals/constants';
import { useDefaultCycleId } from 'src/pages/dashboard/goals/hooks/useDefaultCycleId';
import { goalsKeys } from 'src/pages/dashboard/goals/queries';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getTeamGoals } from '../services';

import MyTeamGoalsSummary from './components/MyTeamGoalsSummary';
import TeamTable from './components/TeamTable';

const MyTeam = () => {
  const { t } = useLokaliseTranslation('goals');
  const location = useLocation();
  const { state } = location;
  const goalCycleIdFromState = (state as { goalCycleId?: number })?.goalCycleId;
  const defaultCycleId = useDefaultCycleId();

  const form = useForm({
    defaultValues: {
      goalCycleId: goalCycleIdFromState ?? defaultCycleId ?? null,
      query: '',
    },
  });
  const goalCycleId = useWatch({ control: form.control, name: 'goalCycleId' });
  const query = useWatch({ control: form.control, name: 'query' });

  const { pagination, setPage } = useServerPagination({
    labelRowsPerPage: t('general:rows_per_page'),
    defaultLimit: MY_TEAM_PAGE_SIZE,
    limitOptions: [MY_TEAM_PAGE_SIZE],
  });

  const {
    data: allTeamGoals,
    isLoading: isAllTeamGoalsLoading,
    isFetching: isAllTeamGoalsFetching,
  } = useQuery(
    goalsKeys.teamList(Number(goalCycleId), query, pagination),
    () =>
      getTeamGoals(Number(goalCycleId), {
        ...pagination,
        ...(query ? { q: query } : {}),
      }),
    {
      select: r => r.data,
      keepPreviousData: true,
      enabled: !!goalCycleId,
    },
  );
  const goals = allTeamGoals?.items || [];
  const totalPages = allTeamGoals?.totalPages ?? 0;
  const loading =
    isAllTeamGoalsLoading ||
    isAllTeamGoalsFetching ||
    (!!goalCycleId && !allTeamGoals);

  return (
    <Stack sx={{ gap: 3, height: '100%' }}>
      {!!goalCycleId && (
        <MyTeamGoalsSummary
          loading={isAllTeamGoalsLoading}
          goalCycleId={goalCycleId}
        />
      )}
      <FormProvider {...form}>
        <Stack sx={{ gap: 2, flexDirection: 'row', alignItems: 'center' }}>
          <HuSearch
            label={t('general:searching')}
            placeholder={t('my_team.search_placeholder')}
            value={query}
            onChange={value => {
              form.setValue('query', value);
              setPage(0);
            }}
          />
          <CycleSelector onChange={() => setPage(0)} />
        </Stack>
        <TeamTable
          goals={goals}
          loading={loading}
        />
        {totalPages > 1 && (
          <HuPagination
            type="basic"
            limit={pagination.limit}
            page={pagination.page + 1}
            totalPages={totalPages}
            loading={loading}
            onChangePage={newPage => setPage(newPage - 1)}
          />
        )}
      </FormProvider>
    </Stack>
  );
};

export default MyTeam;
