import { type FC, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';
import { useQuery } from 'react-query';

import {
  IconChevronRight,
  IconEdit,
  IconTrash,
  IconUsers,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';

import FormSelectionCard from '@material-hu/components/composed-components/SelectionCard/form';
import Alert from '@material-hu/components/design-system/Alert';
import List from '@material-hu/components/design-system/List';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import RadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';
import Title from '@material-hu/components/design-system/Title';

import { getEventOrganizers } from 'src/services/events';
import { type Event, EventOrganizerStatus } from 'src/types/events';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { truncateText } from 'src/utils/text';
import { getFullName } from 'src/utils/userUtils';

import { useMultipleOrganizerDrawer } from '../../hooks/useMultipleOrganizerDrawer';
import { eventsKeys } from '../../queries';

const MAX_DESCRIPTION_LENGTH = 180;

type Props = {
  event?: Event;
};

export const OrganizersStep: FC<Props> = props => {
  const { event } = props;
  const { t } = useLokaliseTranslation('events');
  const theme = useTheme();
  const { watch, setValue } = useFormContext();
  const { feedPublishPolicy, visibility, groupId } = watch();

  const isEditing = !!event;

  const {
    data: existingOrganizers = [],
    isLoading: isLoadingExistingOrganizers,
  } = useQuery(
    eventsKeys.eventOrganizers(event?.id ?? 0),
    () =>
      getEventOrganizers({
        id: event!.id,
        excludeUserIds: [event!.user.id],
        statuses: [EventOrganizerStatus.ACCEPTED, EventOrganizerStatus.PENDING],
        limit: 20,
      }),
    {
      enabled: isEditing,
      select: res => res.data.items,
    },
  );

  const {
    drawerElements: multipleOrganizerDrawerElements,
    showDrawer: showMultipleOrganizerDrawer,
    selectedUsers,
    setSelectedUsers,
  } = useMultipleOrganizerDrawer({
    selectedGroupId: visibility.group ? groupId : undefined,
  });

  useEffect(() => {
    if (!isEditing) {
      setValue(
        'coOrganizers',
        selectedUsers.map(u => u.id),
      );
    }
  }, [selectedUsers, setValue, isEditing]);

  const getOrganizerDescription = () => {
    const users = isEditing ? existingOrganizers : selectedUsers;

    if (users.length === 0) {
      return t('add_coorganizer_list_description');
    }

    return truncateText(
      users.map(user => getFullName(user)).join(', '),
      MAX_DESCRIPTION_LENGTH,
    );
  };

  return (
    <Stack sx={{ gap: 4 }}>
      {multipleOrganizerDrawerElements}
      <Stack sx={{ gap: 2 }}>
        <Title
          title={t('add_coorganizer_title')}
          description={t('add_coorganizer_description')}
          variant="S"
        />
        {isEditing && (
          <Alert
            title={t('create_event_form.add_coorganizer_list_edit_alert')}
            severity="info"
          />
        )}
        <List
          sx={{
            borderRadius: 2,
            border: `1px solid ${theme.palette.new.border.neutral.default}`,
          }}
        >
          <ListItem
            loading={isLoadingExistingOrganizers}
            avatar={{
              Icon: IconUsers,
            }}
            text={{
              title: t('add_coorganizer_list_title'),
              description: getOrganizerDescription(),
            }}
            slotProps={{
              title: {
                slotProps: {
                  title: {
                    disabled: isEditing,
                  },
                },
              },
            }}
            action={{
              Icon: selectedUsers.length > 0 ? IconEdit : IconChevronRight,
              disabled: isEditing,
              onClick: showMultipleOrganizerDrawer,
            }}
            {...(selectedUsers.length > 0 && {
              action2: {
                Icon: IconTrash,
                disabled: isEditing,
                onClick: () => {
                  setSelectedUsers([]);
                },
              },
            })}
          />
        </List>
      </Stack>
      <Stack sx={{ gap: 2 }}>
        <Title
          title={t('who_can_publish_title')}
          variant="S"
        />
        <Stack sx={{ gap: 2 }}>
          <FormSelectionCard
            sx={{ width: '100%' }}
            name="feedPublishPolicy.all"
            isOnlyOption
          >
            <RadioButton
              label={t('all_invites_title')}
              description={t('all_invites_description')}
              size="small"
              isActive={feedPublishPolicy.all}
            />
          </FormSelectionCard>
          <FormSelectionCard
            sx={{ width: '100%' }}
            name="feedPublishPolicy.organizers"
            isOnlyOption
          >
            <RadioButton
              label={t('only_organizers_title')}
              description={t('only_organizers_description')}
              size="small"
              isActive={feedPublishPolicy.organizers}
            />
          </FormSelectionCard>
        </Stack>
      </Stack>
    </Stack>
  );
};

export default OrganizersStep;
