import { useEffect } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import {
  IconBuildingSkyscraper,
  IconUserOff,
  IconUsers,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import SelectionCard from '@material-hu/components/composed-components/SelectionCard';
import Avatar from '@material-hu/components/design-system/Avatar';
import Pills from '@material-hu/components/design-system/Pills';
import Skeleton from '@material-hu/components/design-system/Skeleton';
import Title from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  useInfiniteRegionUsersSearch,
  useRegionUsersSearch,
  useUsersPublicSearch,
} from 'src/services/usersQueries';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormEmployeesSelection from 'src/components/FormInputs/FormEmployeesSelection';

import { CollabSelection } from '../constants';

type Props = {
  isEdit?: boolean;
  isLoading?: boolean;
  title?: string;
  subtitle?: string;
  regionId?: number;
  totalUsers?: number[];
};

const getIconForSelection = (value: CollabSelection) => {
  switch (value) {
    case CollabSelection.ALL_USERS:
      return IconBuildingSkyscraper;
    case CollabSelection.TARGETED_USERS:
      return IconUsers;
    case CollabSelection.NONE:
    default:
      return IconUserOff;
  }
};

const PeopleStepSkeleton = () => {
  return (
    <Stack sx={{ gap: 2 }}>
      <Skeleton height={76} />
      <Skeleton height={76} />
      <Skeleton height={76} />
    </Stack>
  );
};

const PeopleStep = ({
  isLoading = false,
  regionId,
  subtitle,
  title,
  totalUsers,
}: Props) => {
  const HuGoThemeProvider = useHuGoTheme();
  const { t } = useLokaliseTranslation(['regions', 'work_schedules']);
  const { resetField, getValues, setValue, control } = useFormContext();

  const regionsUserMode = useWatch({ control, name: 'regionsUserMode' });

  const regionSearchResult = useRegionUsersSearch(
    { search: '', regionId },
    { enabled: !!regionId },
  );
  const publicSearchResult = useUsersPublicSearch({
    extraUseQueryParams: { enabled: !regionId },
  });
  const {
    data: usersData,
    isLoading: isLoadingUsers,
    isFetching: isFetchingUsers,
  } = regionId ? regionSearchResult : publicSearchResult;

  const selectionOptions = Object.values(CollabSelection).map(value => ({
    value,
    label: t(`${regionId ? 'regions_sites' : 'regions'}:${value}`),
    helperText: t(`${regionId ? 'regions_sites' : 'regions'}:${value}_INFO`, {
      count: usersData?.data?.count,
    }),
    icon: getIconForSelection(value),
    chipLabel:
      value === CollabSelection.ALL_USERS
        ? t('work_schedules:automatic_update')
        : undefined,
  }));

  const customUserSearch = regionId
    ? (searchParams: Record<string, unknown>) =>
        useInfiniteRegionUsersSearch({
          regionId,
          ...searchParams,
        } as any)
    : undefined;

  useEffect(() => {
    if (regionsUserMode !== CollabSelection.TARGETED_USERS) {
      resetField('userIds');
    }
  }, [regionsUserMode]);

  useEffect(() => {
    return () => {
      if (getValues('regionsUserMode') === CollabSelection.TARGETED_USERS) {
        resetField('regionsUserMode');
        resetField('userIds');
      }
    };
  }, []);

  if (isLoadingUsers || isFetchingUsers) {
    return <PeopleStepSkeleton />;
  }

  return (
    <Stack>
      <HuGoThemeProvider>
        {title && subtitle && (
          <Title
            title={title}
            description={subtitle}
            variant="L"
            sx={{ mb: 4 }}
          />
        )}
        <Stack sx={{ gap: 2 }}>
          {selectionOptions.map(option => (
            <SelectionCard
              key={option.value}
              fullWidth
              checked={regionsUserMode === option.value}
              disabled={isLoading}
              onClick={() => {
                setValue('regionsUserMode', option.value, {
                  shouldDirty: true,
                  shouldTouch: true,
                  shouldValidate: true,
                });
              }}
              sx={{
                '& .MuiCardContent-root': {
                  display: 'flex',
                  flexDirection: 'row',
                  gap: 1,
                  alignItems: 'center',
                },
              }}
            >
              <Avatar Icon={option.icon} />
              <Title
                title={option.label}
                description={option.helperText}
                variant="S"
                sx={{ flex: 1, maxWidth: '90ch' }}
              />
              {option.chipLabel && (
                <Stack sx={{ marginLeft: 'auto' }}>
                  <Pills
                    label={option.chipLabel}
                    hasIcon={false}
                    type="highlight"
                  />
                </Stack>
              )}
            </SelectionCard>
          ))}
        </Stack>
      </HuGoThemeProvider>
      {regionsUserMode === CollabSelection.TARGETED_USERS && (
        <Stack sx={{ mt: 4, mb: 8 }}>
          <FormEmployeesSelection
            name="userIds"
            participantsLabel={t('regions:people')}
            searchLabel={t('regions:search_people')}
            useCustomUserSearch={customUserSearch}
            usersPool={totalUsers}
          />
        </Stack>
      )}
    </Stack>
  );
};

export default PeopleStep;
