import { type FC, useEffect, useRef } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useLocation, useNavigate } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import { styled, useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useAuth } from 'src/contexts/JWTContext';
import { useSocket } from 'src/contexts/SocketContext';
import useForm from 'src/hooks/queryHooks/form';
import useGeneralError from 'src/hooks/useGeneralError';
import { getStatsForms } from 'src/services/forms';
import { FormType } from 'src/types/forms';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import Badge from 'src/components/Badge';
import FormList from 'src/components/dashboard/form/FormList';
import FormListAvailableItem from 'src/components/dashboard/form/FormListAvailableItem';
import FormListCompletedItem from 'src/components/dashboard/form/FormListCompletedItem';
import {
  formKeys,
  updateFormsNotifications,
} from 'src/components/dashboard/form/queries';
import { formRoutes } from 'src/components/dashboard/form/routes';
import SearchBar from 'src/components/search/SearchBar';
import Tabs from 'src/components/tabs';

const ButtonRequest = styled(Button)(({ theme }) => ({
  marginTop: '20px',
  color: theme.palette.new.text.neutral.default,
  backgroundColor: theme.palette.new.background.elements.grey,
  width: 'fit-content',
  '&:hover': {
    backgroundColor: theme.palette.new.action.background.neutral.hover,
  },
}));

const Container = styled(Box)(({ theme }) => ({
  overflowY: 'hidden',
  height: '90vh',
  '& .tabs': {
    backgroundColor: theme.palette.new.background.layout.tertiary,
  },
}));

type LocationState = {
  toCompletedTab: number;
};

const LIMIT = 20;

const Forms: FC = () => {
  const rootRef = useRef<any>(null);

  const { t } = useLokaliseTranslation(['forms', 'screens']);
  const theme = useTheme();

  const { user } = useAuth();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();
  const socket = useSocket();
  const { state } = useLocation();
  const { formsAvailable, formsCompleted, query, setQuery } = useForm();

  useEffect(() => window.history.replaceState({}, document.title), []);

  const stateLocation = state as LocationState;

  const dataFormsCompleted = formsCompleted(user?.id, FormType.FORM, LIMIT);

  const dataFormsAvailable = formsAvailable(FormType.FORM, LIMIT);

  const formsStats = useQuery(formKeys.stats(), () => getStatsForms(user?.id), {
    onError: err => showGeneralError(err, t('ERROR_GET_STATS_FORMS')),
  });

  useEffect(() => {
    socket.listenEvent(
      EVENTS_SOCKETS.NEW_FORM_CHAT_CREATED,
      updateFormsNotifications,
    );

    socket.listenEvent(
      EVENTS_SOCKETS.APPROVAL_FORM_CLOSED,
      updateFormsNotifications,
    );

    socket.listenEvent(
      EVENTS_SOCKETS.NEW_FORM_CHAT_MESSAGE_AGENT,
      updateFormsNotifications,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.NEW_FORM_CHAT_CREATED,
        updateFormsNotifications,
      );

      socket.closeEvent(
        EVENTS_SOCKETS.APPROVAL_FORM_CLOSED,
        updateFormsNotifications,
      );

      socket.closeEvent(
        EVENTS_SOCKETS.NEW_FORM_CHAT_MESSAGE_AGENT,
        updateFormsNotifications,
      );
    };
  }, [socket]);

  const formStats = formsStats?.data?.data;

  const navigateToFormsRequests = () => {
    navigate(formRoutes.requests.general(FormType.FORM));
  };

  const handleFilterChange = (value: any) => setQuery(value);

  const tabs = [
    {
      id: t('AVAILABLE'),
      title: t('AVAILABLE'),
      content: (
        <FormList
          rootRef={rootRef}
          noResultsLabel={t('NO_FORMS_AVAILABLE')}
          ListItem={FormListAvailableItem}
          type="FORM"
          {...dataFormsAvailable}
        />
      ),
    },
    {
      id: t('COMPLETED'),
      title: (
        <>
          {t('COMPLETED')}
          <Badge count={formStats?.unreadFinished || 0} />
        </>
      ),
      content: (
        <FormList
          rootRef={rootRef}
          noResultsLabel={t('NO_FORMS_COMPLETED')}
          ListItem={FormListCompletedItem}
          type="FORM"
          {...dataFormsCompleted}
        />
      ),
    },
  ];

  const navbarHeight =
    document.getElementById('dashboard-navbar')?.offsetHeight || 0;

  const formsSearchBoxHeight =
    document.getElementById('forms-searchbox')?.offsetHeight || 0;

  const formsTabsHeight =
    document.getElementById('forms-tabs')?.offsetHeight || 0;

  return (
    <>
      <Helmet>
        <title> {formatTitle(t('screens:Forms'))}</title>
      </Helmet>
      <Container
        ref={rootRef}
        sx={{ maxHeight: '100%' }}
      >
        <Box
          id="forms-searchbox"
          sx={{ backgroundColor: theme.palette.new.background.layout.tertiary }}
        >
          {formStats?.isResponsible && (
            <Box textAlign="center">
              <ButtonRequest
                variant="contained"
                size="large"
                color="primary"
                onClick={navigateToFormsRequests}
                endIcon={
                  <Badge
                    style={{ fontSize: '1em' }}
                    count={
                      formStats?.unassignedForms +
                      formStats?.unreadAssignedFormChatMessages
                    }
                    limit={100}
                  />
                }
              >
                {t('REQUESTS')}
              </ButtonRequest>
            </Box>
          )}
          <Typography
            color="textPrimary"
            variant="h5"
            sx={{
              py: !formStats?.isResponsible ? 6 : 3,
              mx: 3,
              textAlign: 'center',
              wordWrap: 'break-word',
            }}
          >
            {t('screens:Forms')}
          </Typography>
          <SearchBar
            placeholder={t('SEARCH_FORM')}
            inputProps={{ maxLength: 255 }}
            query={query}
            onChange={handleFilterChange}
          />
        </Box>
        <Tabs
          id="requests"
          tabs={tabs}
          withContainer
          tabDefault={stateLocation?.toCompletedTab}
          tabsProps={{
            id: 'forms-tabs',
            variant: 'fullWidth',
          }}
          tabProps={{
            className: 'tabs',
          }}
          tabPanelProps={{
            sx: {
              maxHeight: `calc(100vh - ${navbarHeight}px - ${formsSearchBoxHeight}px - ${formsTabsHeight}px)`,
              paddingBottom: formStats?.isResponsible ? '50px' : '20px',
            },
            withScrollbar: true,
            options: { suppressScrollX: true },
          }}
        />
      </Container>
    </>
  );
};

export default Forms;
