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

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Divider from '@material-hu/mui/Divider';
import TableContainer from '@material-hu/mui/TableContainer';

import ApproversDialog from 'src/pages/dashboard/recognitions/components/ApproversDialog';
import FilterIdeas from 'src/pages/dashboard/recognitions/components/FilterIdeas';
import IdeasSearch from 'src/pages/dashboard/recognitions/components/IdeasSearch';
import IdeasTable from 'src/pages/dashboard/recognitions/components/IdeasTable';
import ModuleHeader from 'src/pages/dashboard/recognitions/components/ModuleHeader';
import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import { recognitionsKeys } from 'src/pages/dashboard/recognitions/queries';
import { recognitionsRoutes } from 'src/pages/dashboard/recognitions/routes';
import { getEmployeeIdeas, getIdeasApprovals } from 'src/services/recognitions';
import {
  parseDate,
  filterByDate,
  filterByParam,
  getUserId,
} from 'src/utils/recognitions';

import GoBackButton from 'src/components/dashboard/GoBackButton';

const Ideas: FC = () => {
  const { t } = useTranslation();
  const userId = getUserId();
  const navigate = useNavigate();

  const { watch } = useForm();

  const [ideas, setIdeas] = useState(null);
  const [filteredIdeas, setFilteredIdeas] = useState(null);
  const [searchInput, setSearchInput] = useState('');

  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [plantIdea, setPlantIdea] = useState('');
  const [areaIdea, setAreaIdea] = useState('');
  const [status, setStatus] = useState('');

  const [openApproverDialog, setOpenApproverDialog] = useState(false);
  const [currentApprover, setCurrentApprover] = useState(null);

  const handleOpenApproverDialog = () => setOpenApproverDialog(true);
  const handleCloseApproverDialog = () => setOpenApproverDialog(false);
  const handleSelectCurrentApprover = approver => setCurrentApprover(approver);

  const [openIdeaFilter, setOpenIdeaFilter] = useState(false);

  const handleOpenIdeaFilters = () => setOpenIdeaFilter(true);

  const combineIdeasWithApprovers = (ideasToCombine, approvers) => {
    return ideasToCombine?.map(idea => {
      return {
        ...idea,
        approvers: approvers?.filter(approver => approver.folio === idea.folio),
      };
    });
  };

  const { data: ideasApprovers, isLoading: isIdeasApproversLoading } = useQuery(
    [recognitionsKeys.ideasApprovers(userId)],
    () => getIdeasApprovals(userId),
    {
      enabled: !!userId,
    },
  );

  const { isLoading } = useQuery(
    [recognitionsKeys.ideas(userId)],
    () =>
      getEmployeeIdeas(userId, parseDate(watch('startDate')), watch('endDate')),
    {
      enabled: !!userId && !!ideasApprovers,
      onSuccess: data => {
        setIdeas(
          combineIdeasWithApprovers(
            JSON.parse(data.data.Data),
            ideasApprovers?.data?.DataApproval,
          ),
        );
        setFilteredIdeas(
          combineIdeasWithApprovers(
            JSON.parse(data.data.Data),
            ideasApprovers?.data?.DataApproval,
          ),
        );
      },
    },
  );

  const applyFiltersAndSearch = () => {
    let sorted = [...ideas];
    sorted = filterByDate(sorted, startDate, endDate);
    sorted = filterByParam(sorted, 'status', status);
    sorted = filterByParam(sorted, 'ideaPlantID', plantIdea);
    sorted = filterByParam(sorted, 'ideaAreaID', areaIdea);
    const lowerCaseSearch = searchInput.toLowerCase();
    sorted = sorted.filter(idea =>
      idea.ideaTitle.toLowerCase().includes(lowerCaseSearch),
    );
    setFilteredIdeas(sorted);
  };

  useEffect(() => {
    if (ideas && ideasApprovers) {
      applyFiltersAndSearch();
    }
  }, [
    searchInput,
    startDate,
    endDate,
    plantIdea,
    areaIdea,
    status,
    ideas,
    ideasApprovers,
  ]);

  const onApplyFilters = data => {
    setStartDate(data.startDate);
    setEndDate(data.endDate);
    setPlantIdea(data.ideaPlant);
    setAreaIdea(data.ideaArea);
    setStatus(data.status);
  };

  const handleSearchInputChange = event => setSearchInput(event.target.value);

  const handleGoBack = () => navigate(recognitionsRoutes.home());

  if (!userId) {
    navigate(recognitionsRoutes.home());
  }

  return (
    <>
      <Helmet>
        <title>{t('RECOGNITIONS')}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 3,
          pb: 3,
        }}
      >
        <Container maxWidth="md">
          <GoBackButton onClick={handleGoBack} />
          <Box sx={{ mt: 3, mb: 3 }}>
            <Box
              sx={{
                p: 3,
                width: '100%',
                backgroundColor: '#ffffff',
                borderRadius: '10px',
              }}
            >
              <>
                <ModuleHeader title={t('MY_IDEAS')} />
                <Divider sx={{ borderBottomWidth: 'medium', mt: 2, mb: 3 }} />
                {(isLoading || isIdeasApproversLoading) && (
                  <Box sx={{ textAlign: 'center' }}>
                    <CircularProgress />
                  </Box>
                )}
                {!isLoading && !isIdeasApproversLoading && filteredIdeas && (
                  <Box>
                    <IdeasSearch
                      searchInput={searchInput}
                      handleOnChange={handleSearchInputChange}
                      onOpenIdeaFilter={handleOpenIdeaFilters}
                      placeholder={t('SEARCH_IDEAS')}
                    />
                    <TableContainer>
                      <IdeasTable
                        ideas={filteredIdeas}
                        onSelectCurrentApprover={handleSelectCurrentApprover}
                        onOpenApproverDialog={handleOpenApproverDialog}
                      />
                    </TableContainer>
                    <FilterIdeas
                      open={openIdeaFilter}
                      onClose={() => setOpenIdeaFilter(false)}
                      onApplyFilters={onApplyFilters}
                    />
                  </Box>
                )}
              </>
            </Box>
          </Box>
          {openApproverDialog && currentApprover && (
            <ApproversDialog
              open={openApproverDialog}
              approvers={currentApprover}
              onClose={handleCloseApproverDialog}
            />
          )}
        </Container>
      </Box>
    </>
  );
};

export default Ideas;
