import { FC, Fragment, useState, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { useForm, FormProvider } from 'react-hook-form';
import { useLocation, useParams, useNavigate } from 'react-router-dom';

import FilterListIcon from '@material-hu/icons/material/FilterList';
import Box from '@material-hu/mui/Box';
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 useCustomServerTranslation from 'src/hooks/useCustomServerTranslation';
import useNewTheme from 'src/hooks/useNewTheme';
import GoBackButton from 'src/pages/dashboard/scorm/components/GoBackButton';
import ScormCard from 'src/pages/dashboard/scorm/components/ScormCard';
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 { scormRoutes } from 'src/pages/dashboard/scorm/routes';
import { ScormProgressType, CoursesType } from 'src/types/scorm';
import { getCoursesByTitle, getCoursesByState } from 'src/utils/scorm';

const Courses: FC = () => {
  const { folderId } = useParams();
  const location = useLocation();
  const { courses } = (location.state as CoursesType) || {};
  const NewThemeProvider = useNewTheme();
  const { t } = useTranslation();
  const navigate = useNavigate();

  const [openFilters, setOpenFilters] = useState(false);
  const [selectedFilters, setSelectedFilters] = useState([]);
  const [filteredCourses, setFilteredCourses] = useState([]);

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

  const { watch } = form;

  useEffect(() => {
    if (courses) {
      const searchQuery = watch('search');
      const filtered = courses.filter(
        course =>
          getCoursesByTitle(course.title, searchQuery) &&
          getCoursesByState(selectedFilters, course.registerData, t),
      );
      setFilteredCourses(filtered);
    }
  }, [courses, watch('search'), selectedFilters]);

  const handleOnClickBack = () => navigate(scormRoutes.all());

  const handleSaveFilters = currentFilters =>
    setSelectedFilters(currentFilters);

  const states = Object.values(ScormProgressType).map(value => t(value));

  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,
              }}
            >
              <GoBackButton onClick={handleOnClickBack} />
              <Typography
                color="textPrimary"
                variant="h5"
                component="h1"
              >
                {folderId}
              </Typography>
              <Grid
                container
                sx={{
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <Grid
                  item
                  xs
                >
                  <FormProvider {...form}>
                    <form style={{ width: '100%' }}>
                      <SearchBar title={t('SEARCH_BY_COURSE_NAME')} />
                    </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={states}
                  title={t('COURSE_STATUS')}
                  onClose={() => setOpenFilters(false)}
                  handleSaveFilters={handleSaveFilters}
                  filters={selectedFilters}
                />
              )}
              {filteredCourses.length === 0 && (
                <Stack
                  sx={{
                    width: '100%',
                    alignItems: 'center',
                    mt: 3,
                  }}
                >
                  <Typography
                    variant="subtitle2"
                    color="secondary"
                  >
                    {t('EMPTY_COURSES')}
                  </Typography>
                </Stack>
              )}
              {filteredCourses.length > 0 && (
                <Grid
                  container
                  spacing={3}
                >
                  {filteredCourses?.map(course => (
                    <Grid
                      key={course.id}
                      md={4}
                      xs={12}
                      item
                    >
                      <Fragment key={course.id}>
                        <ScormCard
                          id={course.id}
                          folderName={folderId}
                          title={course.title}
                          state={course.registerData}
                        />
                      </Fragment>
                    </Grid>
                  ))}
                </Grid>
              )}
            </Stack>
          </Box>
        </Container>
      </Box>
    </NewThemeProvider>
  );
};

export default Courses;
