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

import FilterListIcon from '@material-hu/icons/material/FilterList';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Grid from '@material-hu/mui/Grid';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import { encryptStorage } from 'src/config/encrypt-storage';
import { useAuth } from 'src/contexts/JWTContext';
import useCustomServerTranslation from 'src/hooks/useCustomServerTranslation';
import { useMobileLayout } from 'src/hooks/useMobileLayout';
import useNewTheme from 'src/hooks/useNewTheme';
import FolderCard from 'src/pages/dashboard/scorm/components/FolderCard';
import SearchBar from 'src/pages/dashboard/scorm/components/SearchBar';
import ThemeFilters from 'src/pages/dashboard/scorm/components/ThemeFilters';
import { useTranslation } from 'src/pages/dashboard/scorm/i18n';
import { scormKeys } from 'src/pages/dashboard/scorm/queries';
import {
  getCourses,
  getMoreCourses,
  getUserRegistration,
} from 'src/services/scorm';
import {
  addRegistrationStatus,
  getGroupCourses,
  getThemes,
  getCoursesByTitle,
  getCoursesByFilters,
} from 'src/utils/scorm';

export type FoldersProps = {
  isMobile?: boolean;
};

const Folders: FC<FoldersProps> = props => {
  const { isMobile = false } = props;
  const { accessToken } = useParams();
  const { t } = useTranslation();
  const { user, instance } = useAuth();
  const NewThemeProvider = useNewTheme();
  useMobileLayout();

  const [openFilters, setOpenFilters] = useState(false);
  const [selectedFilters, setSelectedFilters] = useState([]);
  const [filteredFolders, setFilteredFolders] = useState([]);

  const form = useForm({
    defaultValues: {
      search: '',
    },
  });
  const { watch } = form;

  useEffect(() => {
    if (accessToken && isMobile) {
      encryptStorage.setItem('accessToken', accessToken);
    }
  }, [accessToken, isMobile]);

  const fetchCourses = async (instanceId, moreToken = null) => {
    let response;
    if (!moreToken) {
      response = await getCourses(instanceId);
    } else {
      response = await getMoreCourses(moreToken);
    }
    if (response.data.more) {
      const nextResponse = await fetchCourses(instanceId, response.data.more);
      return {
        ...response.data,
        courses: [...response.data.courses, ...nextResponse.courses],
      };
    }
    return response.data;
  };

  const { data: coursesData, isLoading: isLoadingCoursesData } = useQuery(
    scormKeys.courses.all(),
    () => fetchCourses(instance.id),
  );

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

  const registrationQueries = useQueries(
    courses?.map(course => ({
      queryKey: scormKeys.courses.detail(course.id),
      queryFn: () => getUserRegistration(course.id, user.id.toString()),
      enabled: !!coursesData && !isLoadingCoursesData,
    })),
  );

  const updatedCoursesData = addRegistrationStatus(
    coursesData?.courses,
    registrationQueries,
  );

  const isLoading =
    registrationQueries?.some(query => query.isLoading) || isLoadingCoursesData;

  const groupedCourses = getGroupCourses(updatedCoursesData);

  useEffect(() => {
    if (groupedCourses) {
      const searchQuery = watch('search');
      const filteredData = groupedCourses.filter(
        course =>
          getCoursesByTitle(course.name, searchQuery) &&
          getCoursesByFilters(selectedFilters, course.name),
      );
      setFilteredFolders(filteredData);
    }
  }, [groupedCourses, watch('search'), selectedFilters]);

  const themes = getThemes(groupedCourses);

  const handleSaveFilters = currentFilters =>
    setSelectedFilters(currentFilters);

  const title = useCustomServerTranslation({
    module: 'COURSES',
    defaultTranslationKey: 'SCORM:COURSES',
  });

  return (
    <NewThemeProvider>
      <Helmet>
        <title>{title}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 3,
          pb: 3,
        }}
      >
        <Container sx={{ maxWidth: '1100px !important' }}>
          <Box sx={{ mt: 3, mb: 3 }}>
            <Stack
              sx={{
                px: 1,
                gap: 3,
              }}
            >
              <Typography
                color="textPrimary"
                variant="h5"
                component="h1"
              >
                {t('TRAININGS')}
              </Typography>
              <Grid
                container
                sx={{
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <Grid
                  item
                  xs
                >
                  <FormProvider {...form}>
                    <form style={{ width: '100%' }}>
                      <SearchBar title={t('SEARCH_BY_THEME')} />
                    </form>
                  </FormProvider>
                </Grid>
                <Grid
                  item
                  sx={{ ml: 4 }}
                >
                  <Button
                    startIcon={<FilterListIcon fontSize="small" />}
                    variant="outlined"
                    onClick={() => setOpenFilters(true)}
                    sx={{ px: 4 }}
                  >
                    {t('FILTER_BY')}
                  </Button>
                </Grid>
              </Grid>
              {openFilters && (
                <ThemeFilters
                  open={openFilters}
                  themes={themes}
                  title={t('THEME')}
                  onClose={() => setOpenFilters(false)}
                  handleSaveFilters={handleSaveFilters}
                  filters={selectedFilters}
                />
              )}
              {isLoading && (
                <Stack
                  sx={{
                    mt: 4,
                    width: '100%',
                    flexDirection: 'row',
                    justifyContent: 'center',
                  }}
                >
                  <CircularProgress />
                </Stack>
              )}
              {!isLoading && courses.length === 0 && (
                <Stack
                  sx={{
                    width: '100%',
                    alignItems: 'center',
                    mt: 3,
                  }}
                >
                  <Typography
                    variant="subtitle2"
                    color="secondary"
                  >
                    {t('EMPTY_COURSES')}
                  </Typography>
                </Stack>
              )}
              {!isLoading && courses.length > 0 && (
                <Grid
                  container
                  spacing={3}
                >
                  {filteredFolders?.map(course => (
                    <Grid
                      key={course.id}
                      md={4}
                      xs={12}
                      item
                    >
                      <FolderCard folder={course} />
                    </Grid>
                  ))}
                </Grid>
              )}
            </Stack>
          </Box>
        </Container>
      </Box>
    </NewThemeProvider>
  );
};

export default Folders;
