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 useCoursesTitle from '../hooks/useCoursesTitle';
import {
  type TParams as GetCoursesParams,
  useGetCourses,
} from '../hooks/useGetCourses';
import {
  CourseCategories,
  type CourseFilters,
  CourseOrderBy,
  CourseStatus,
} from '../types';

import { CourseCard } from './components/CourseCard';
import CourseCardSkeleton from './components/CourseCardSkeleton';
import CourseCategoryFilter from './components/CourseCategoryFilter';
import CourseFilter from './components/CourseFilter';
import { CourseListStateCard } from './components/CourseListStateCard';

const defaultFilters = {
  status: CourseStatus.ALL,
  category: CourseCategories.ALL,
};

const CoursesList = () => {
  const { t } = useLokaliseTranslation('learning');
  const title = useCoursesTitle();

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

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

  const getCoursesParams = params as GetCoursesParams;

  const {
    data: coursesData,
    isPreviousData,
    isLoading,
    isSuccess,
    state,
    refetch,
  } = useGetCourses(getCoursesParams);

  const handleChangeFilters = (filters: CourseFilters) => {
    setPartialParams(filters, true);
  };

  const handleTabChange = (newTab: CourseStatus) => {
    setPartialParams({ status: newTab }, true);
  };

  const handleCategoryChange = (newCategory: string) => {
    setPartialParams({ category: newCategory }, true);
  };

  const handleRetry = () => refetch();

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

  const courses = coursesData?.items || [];

  const showList = isLoading || isSuccess;

  return (
    <BaseLayout title={title}>
      <FormProvider {...form}>
        <ListLayout
          title={title}
          sidebar={
            <CourseCategoryFilter
              value={getCoursesParams.category}
              onChange={handleCategoryChange}
            />
          }
          tabs={
            <Tabs
              value={getCoursesParams.status}
              onTabChange={value => handleTabChange(value as CourseStatus)}
              tabs={tabs}
            />
          }
          search={
            <Search
              inputProps={{
                placeholder: t('course.search'),
              }}
            />
          }
          filter={
            <CourseFilter
              onChange={handleChangeFilters}
              params={getCoursesParams}
            />
          }
        >
          {showList && (
            <>
              <Grid
                container
                rowSpacing={3}
                columnSpacing={2}
                sx={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
                  opacity: isPreviousData ? 0.5 : 1,
                }}
              >
                {isLoading &&
                  times(6, String).map(course => (
                    <CourseCardSkeleton key={course} />
                  ))}
                {!isLoading &&
                  courses.map(course => (
                    <CourseCard
                      key={course.id}
                      course={course}
                    />
                  ))}
              </Grid>
              <Pagination
                inputProps={{
                  loading: isLoading,
                  totalPages: coursesData?.totalPages,
                }}
              />
            </>
          )}
          <CourseListStateCard
            state={state}
            status={getCoursesParams.status}
            onRetry={handleRetry}
          />
        </ListLayout>
      </FormProvider>
    </BaseLayout>
  );
};

export default CoursesList;
