import { useRef, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import { IconBook, IconUsersPlus } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import useMediaQuery from '@material-hu/mui/useMediaQuery';

import HuAlert from '@material-hu/components/design-system/Alert';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete';
import HuTitle from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { RoleState } from 'src/pages/dashboard/RolesAndPermissions/types';
import { insertIf } from 'src/utils/arrayUtils';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import RolesAndPermissionsTable from './components/RolesAndPermissionsTable';
import useInfiniteRolesSearch from './hooks/useInfiniteRolesSearch';
import useRolesInProgress from './hooks/useRolesInProgress';
import useRolesPermissions from './hooks/useRolesPermissions';
import useTutorialModal from './hooks/useTutorialModal';
import { rolesAndPermissionsRoutes } from './routes';

const RolesAndPermissions = () => {
  const { t } = useLokaliseTranslation('rolesAndPermissions');
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();
  const pageRef = useRef<HTMLDivElement>(null);
  const theme = useTheme();
  const isDownMd = useMediaQuery(theme.breakpoints.down('md'));
  const isDownLg = useMediaQuery(theme.breakpoints.down('lg'));
  const { canManageOrDefineRoles } = useRolesPermissions();
  const [isRefetchingManually, setIsRefetchingManually] = useState(false);

  const {
    search: { component: Search, value: search, state },
    table: { results: roles, totalCount },
    loading: { isLoading, isFetchingNextPage },
    actions: { fetchNextPage, setState, refetch },
    form,
  } = useInfiniteRolesSearch();

  const { rolesInProgressCount, refetch: refetchRolesInProgress } =
    useRolesInProgress();

  const ROLES_AND_PERMISSIONS_OPTIONS = [
    ...insertIf(canManageOrDefineRoles, {
      label: t('general:all'),
      value: 'ALL',
    }),
    {
      label: t('general:states.active'),
      value: RoleState.ACTIVE,
    },
    ...insertIf(canManageOrDefineRoles, {
      label: t('general:states.draft'),
      value: RoleState.DRAFT,
    }),
  ];

  const handleChangeState = (value: string) =>
    setState(value === 'ALL' ? null : (value as RoleState));

  const selectedStateOption =
    ROLES_AND_PERMISSIONS_OPTIONS.find(opt => opt.value === (state || 'ALL')) ??
    ROLES_AND_PERMISSIONS_OPTIONS[0];

  const handleScrollToTop = () => {
    pageRef.current?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  };

  const handleRefetch = async () => {
    setIsRefetchingManually(true);
    try {
      await Promise.all([refetch(), refetchRolesInProgress()]);
    } finally {
      setIsRefetchingManually(false);
    }
  };

  const { modal: tutorialModal, showModal: showTutorialModal } =
    useTutorialModal();

  const showFilterEmptyState = roles?.length === 0 && (!!search || !!state);

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('title'))}</title>
      </Helmet>
      <HuGoThemeProvider>
        {tutorialModal}
        <Stack
          sx={{
            backgroundColor: theme.palette.new.background.layout.default,
            minHeight: '100%',
            px: 12,
            py: 5,
            gap: 2,
          }}
          ref={pageRef}
        >
          <Stack
            sx={{
              gap: 2,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              mb: 2,
            }}
          >
            <HuTitle
              sx={{ minWidth: 200, flex: 1 }}
              variant="L"
              title={t('title')}
              description={t('description')}
            />
            <Stack
              sx={{
                flexDirection: 'row',
                gap: 1.5,
                justifyContent: 'flex-end',
                ...(isDownLg && {
                  flexDirection: 'column',
                }),
                ...(isDownMd && {
                  alignItems: 'flex-end',
                }),
              }}
            >
              <Button
                variant="secondary"
                size="large"
                startIcon={<IconBook size={16} />}
                onClick={showTutorialModal}
              >
                {t('tutorial.view_tutorial')}
              </Button>
              {canManageOrDefineRoles && (
                <Button
                  variant="primary"
                  size="large"
                  startIcon={<IconUsersPlus size={16} />}
                  onClick={() => navigate(rolesAndPermissionsRoutes.new())}
                  sx={{ minWidth: 225 }}
                >
                  {t('create_role')}
                </Button>
              )}
            </Stack>
          </Stack>
          {rolesInProgressCount > 0 && (
            <HuAlert
              title={t('alert.role_in_progress_title', {
                count: rolesInProgressCount,
              })}
              description={t('alert.role_in_progress_description')}
              severity="info"
              action={{
                text: t('general:update'),
                onClick: () => {
                  if (!isRefetchingManually) handleRefetch();
                },
              }}
              sx={{ mb: 1 }}
            />
          )}
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 2,
              alignItems: 'center',
              mb: 1,
            }}
          >
            <FormProvider {...form}>
              <Search
                inputProps={{
                  placeholder: t('search_role_placeholder'),
                  label: t('general:searching'),
                  sx: { flex: 0.75 },
                }}
              />
            </FormProvider>
            <Stack sx={{ flex: 0.25 }}>
              <HuAutocomplete
                label={t('role_state_label')}
                value={selectedStateOption}
                options={ROLES_AND_PERMISSIONS_OPTIONS}
                onChange={option => handleChangeState(option?.value ?? 'ALL')}
                disableClearable
              />
            </Stack>
          </Stack>
          <RolesAndPermissionsTable
            onScrollToTop={handleScrollToTop}
            query={search}
            state={state || 'ALL'}
            roles={roles}
            isLoading={isLoading || isRefetchingManually}
            isFetchingNextPage={isFetchingNextPage}
            fetchNextPage={fetchNextPage}
            totalCount={totalCount}
            showFilterEmptyState={showFilterEmptyState}
          />
        </Stack>
      </HuGoThemeProvider>
    </>
  );
};

export default RolesAndPermissions;
