import { useState } from 'react';
import { type UseQueryResult } from 'react-query';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconChevronDown } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { type SegmentationGroup } from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type TwoFieldGroup } from 'src/components/AdvancedFilter/types';

import CollapsibleGroupSelector from '@material-hu/components/composed-components/CollapsibleGroupSelector';
import { type BaseUser, FormUserAutocomplete } from './FormUserAutocomplete';
import { toCollapsibleSelectorGroups } from './toCollapsibleSelectorGroups';
import FormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';

enum FilterOption {
  COLLABORATORS = 'COLLABORATORS',
  SEGMENTATIONS = 'SEGMENTATIONS',
  SITES = 'SITES',
}

type Props = {
  segmentationGroups: SegmentationGroup[];
  regions: TwoFieldGroup[];
  isLoadingSegmentations: boolean;
  isLoadingRegions: boolean;
  handleApply: () => void;
  clearFilters: () => void;
  disabledClearButton: boolean;
  clearDraftValues: () => void;
  hideSites?: boolean;
  showIncludeDeactivated?: boolean;
  usersQuery: (search: string) => UseQueryResult<BaseUser[]>;
};

export const useFiltersDrawer = (props: Props) => {
  const {
    segmentationGroups,
    regions,
    isLoadingSegmentations,
    isLoadingRegions,
    handleApply,
    clearFilters,
    disabledClearButton,
    clearDraftValues,
    hideSites = false,
    showIncludeDeactivated = false,
    usersQuery,
  } = props;

  const [openFilter, setOpenFilter] = useState<FilterOption | null>(null);
  const { t } = useLokaliseTranslation([
    'time_tracker',
    'general',
    'regions_sites',
  ]);

  const handleAccordionExpand = (expanded: boolean, filter: FilterOption) => {
    setOpenFilter(expanded ? filter : null);
  };

  const {
    showDrawer: showFiltersDrawer,
    drawer: filtersDrawer,
    closeDrawer: closeFiltersDrawer,
  } = useDrawerV2<{}>(() => {
    return {
      children: (
        <Stack sx={{ overflow: 'auto', flex: 1, px: 2 }}>
          <Stack
            sx={{
              mb: 2,
              p: 2,
              borderRadius: ({ spacing }) => spacing(1),
              backgroundColor: ({ palette }) =>
                palette.new.background.layout.default,
            }}
          >
            <Typography
              variant="globalM"
              fontWeight="fontWeightSemiBold"
              sx={{ mb: 2 }}
            >
              {t('general:collaborators')}
            </Typography>
            <FormUserAutocomplete
              name="users"
              placeholder={t('general:search')}
              usersQuery={usersQuery}
              popupIcon={<IconChevronDown size={24} />}
              sx={{
                // Align endAdornment with accordion chevrons
                '.MuiInputAdornment-root .MuiAutocomplete-endAdornment': {
                  right: 16,
                },
              }}
            />
            {showIncludeDeactivated && (
              <Stack sx={{ pt: 2 }}>
                <FormCheckbox
                  name="includeDeactivated"
                  checkBoxProps={{
                    label: t('general:show_disabled_collaborators'),
                  }}
                />
              </Stack>
            )}
          </Stack>
          {!hideSites && (
            <CollapsibleGroupSelector
              sx={{ '& .MuiTypography-root': { mb: 0 } }}
              groups={toCollapsibleSelectorGroups(regions ?? [])}
              isLoading={isLoadingRegions}
              fieldName="siteIds"
              title={t('regions_sites:sites')}
              expanded={openFilter === FilterOption.SITES}
              onExpandedChange={expanded => {
                handleAccordionExpand(expanded, FilterOption.SITES);
              }}
            />
          )}
          <CollapsibleGroupSelector
            sx={{ '& .MuiTypography-root': { mb: 0 }, mt: 2 }}
            groups={toCollapsibleSelectorGroups(segmentationGroups ?? [])}
            isLoading={isLoadingSegmentations}
            fieldName="segmentationItems"
            title={t('general:segmentations')}
            expanded={openFilter === FilterOption.SEGMENTATIONS}
            onExpandedChange={expanded => {
              handleAccordionExpand(expanded, FilterOption.SEGMENTATIONS);
            }}
          />
        </Stack>
      ),
      title: t('general:filter_by'),
      onClose: () => {
        clearDraftValues();
        closeFiltersDrawer();
      },
      primaryButtonProps: {
        children: t('general:apply'),
        fullWidth: true,
        onClick: () => {
          handleApply();
          closeFiltersDrawer();
        },
      },
      secondaryButtonProps: {
        children: t('general:clean_selection'),
        fullWidth: true,
        onClick: clearFilters,
        disabled: disabledClearButton,
      },
    };
  });

  return {
    showFiltersDrawer,
    filtersDrawer,
    closeFiltersDrawer,
  };
};
