import { useEffect } from 'react';
import { FormProvider } from 'react-hook-form';

import { times } from 'lodash-es';
import { useHuPagination } from '@material-hu/hooks/useHuPagination';
import Grid from '@material-hu/mui/Grid';

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

import { logEvent } from 'src/config/logging';
import BaseLayout from 'src/pages/dashboard/learning/common/components/BaseLayout';
import ListLayout from 'src/pages/dashboard/learning/common/components/ListLayout';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  type TParams as GetPathsParams,
  useGetPaths,
} from '../hooks/useGetPaths';
import usePathsTitle from '../hooks/usePathsTitle';
import { PathOrderBy, PathStatus } from '../types';
import { getStatusOrderBy } from '../utils';

import PathCard from './components/PathCard';
import PathCardSkeleton from './components/PathCardSkeleton';
import PathListStateCard from './components/PathListStateCard';

const defaultFilters = {
  status: PathStatus.ALL,
};

const PathsList = () => {
  const { t } = useLokaliseTranslation('learning');
  const title = usePathsTitle();
  const titleLong = usePathsTitle('learning:path.title_long');

  useEffect(() => {
    logEvent(EventName.PATH_MINIAPP_ENTERED);
  }, []);

  const { Search, Pagination, params, form, setPartialParams } =
    useHuPagination({
      limitOptions: [10, 20],
      defaultOrderBy: PathOrderBy.DEFAULT,
      defaultFilters,
    });

  const getPathsParams = params as GetPathsParams;

  const {
    data: pathsData,
    isPreviousData,
    isLoading,
    isSuccess,
    state,
    refetch,
  } = useGetPaths(getPathsParams);

  const handleTabChange = (newTab: string) => {
    const status = newTab as PathStatus;

    setPartialParams({ status, orderBy: getStatusOrderBy(status) }, true);
  };

  const handleRetry = () => refetch();

  const tabs = [
    PathStatus.ALL,
    PathStatus.PENDING,
    PathStatus.IN_PROGRESS,
    PathStatus.FINISHED,
  ].map(value => ({ value, label: t(`path.tabs.${value}`) }));

  const paths = pathsData?.items || [];

  const showList = isLoading || isSuccess;

  return (
    <BaseLayout title={title}>
      <FormProvider {...form}>
        <ListLayout
          title={titleLong}
          tabs={
            <Tabs
              value={getPathsParams.status}
              onTabChange={handleTabChange}
              tabs={tabs}
            />
          }
          search={<Search inputProps={{ placeholder: t('path.search') }} />}
        >
          {showList && (
            <>
              <Grid
                container
                spacing={3}
                sx={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(auto-fill, minmax(328px, 1fr))',
                  opacity: isPreviousData ? 0.5 : 1,
                }}
              >
                {!isLoading &&
                  paths.map(path => (
                    <Grid
                      key={path.id}
                      item
                      xs
                    >
                      <PathCard path={path} />
                    </Grid>
                  ))}
                {isLoading &&
                  times(9, path => (
                    <Grid
                      key={path}
                      item
                      xs
                    >
                      <PathCardSkeleton />
                    </Grid>
                  ))}
              </Grid>
              <Pagination
                inputProps={{
                  loading: isLoading,
                  totalPages: pathsData?.totalPages,
                }}
              />
            </>
          )}
          <PathListStateCard
            state={state}
            status={getPathsParams.status}
            onRetry={handleRetry}
          />
        </ListLayout>
      </FormProvider>
    </BaseLayout>
  );
};

export default PathsList;
