import { useState } from 'react';
import { useMutation } from 'react-query';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconTrash, IconZoomExclamation } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';

import StateCard from '@material-hu/components/composed-components/StateCard';
import Alert from '@material-hu/components/design-system/Alert';
import Search from '@material-hu/components/design-system/Inputs/Search';
import List from '@material-hu/components/design-system/List';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';

import { ORGANIZER_LIMIT } from 'src/constants/events';
import { addEventOrganizer } from 'src/services/events';
import { type Event } from 'src/types/events';
import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import AddOrganizerDrawer from '../New/components/AddOrganizerDrawer';
import { invalidateEventOrganizers } from '../queries';
import { userInitials } from '../utils';

type UseMultipleOrganizerDrawerProps = {
  event?: Event;
  selectedGroupId?: number;
};

export const useMultipleOrganizerDrawer = (
  params: UseMultipleOrganizerDrawerProps,
) => {
  const { event, selectedGroupId } = params;
  const { t } = useLokaliseTranslation('events');
  const theme = useTheme();

  const [selectedUsers, setSelectedUsers] = useState<User[]>([]);
  const [tempSelectedUsers, setTempSelectedUsers] = useState<User[]>([]);
  const [selectedSearch, setSelectedSearch] = useState('');

  const addEventOrganizerMutation = useMutation(
    (variables: { eventId: number; userIds: number[] }) =>
      addEventOrganizer(variables.eventId, variables.userIds),
    {
      onSuccess: () => {
        if (event) {
          invalidateEventOrganizers(event.id, ORGANIZER_LIMIT.CARD_DISPLAY);
          invalidateEventOrganizers(event.id, ORGANIZER_LIMIT.DRAWER_DISPLAY);
        }
        closeMultipleOrganizerDrawer();
      },
    },
  );

  const filteredSelectedUsers = () => {
    if (!selectedSearch) return tempSelectedUsers;
    const searchLower = selectedSearch.toLowerCase();
    return tempSelectedUsers.filter(user => {
      const fullName = getFullName(user).toLowerCase();
      return fullName.includes(searchLower);
    });
  };

  const handleToggleUser = (user: User) => {
    setTempSelectedUsers(prev => {
      const isSelected = prev.some(u => u.id === user.id);
      if (isSelected) {
        return prev.filter(u => u.id !== user.id);
      }
      return [...prev, user];
    });
  };

  const resetTempSelection = () => {
    setTempSelectedUsers(selectedUsers);
  };

  const {
    drawer: selectedOrganizersDrawer,
    showDrawer: showSelectedOrganizersDrawer,
  } = useDrawerV2(() => ({
    hasBackButton: true,
    title: t('selected_collaborators'),
    children: (
      <Stack sx={{ gap: 1 }}>
        <Search
          value={selectedSearch}
          onChange={setSelectedSearch}
          placeholder={t('general:search')}
        />
        <Stack
          sx={{
            backgroundColor: theme.palette.new.background.layout.default,
            borderRadius: 2,
          }}
        >
          <List sx={{ backgroundColor: 'transparent' }}>
            {filteredSelectedUsers().map(user => (
              <ListItem
                key={user.id}
                avatar={{
                  src: user.profilePicture || undefined,
                  text: !user.profilePicture ? userInitials(user) : undefined,
                }}
                text={{ title: getFullName(user) }}
                action={{
                  Icon: IconTrash,
                  onClick: () => handleToggleUser(user),
                }}
              />
            ))}
          </List>
        </Stack>
        {filteredSelectedUsers().length === 0 && (
          <StateCard
            slotProps={{
              avatar: { Icon: IconZoomExclamation },
              title: {
                title: t('no_users_found_title'),
                description: t('no_users_found_description'),
              },
            }}
            cardContained={false}
          />
        )}
      </Stack>
    ),
  }));

  const {
    drawer: multipleOrganizerDrawer,
    showDrawer: showMultipleOrganizerDrawer,
    closeDrawer: closeMultipleOrganizerDrawer,
  } = useDrawerV2(() => ({
    title: t('add_coorganizer_list_title'),
    children: (
      <AddOrganizerDrawer
        selectedUsers={tempSelectedUsers}
        onToggleUser={handleToggleUser}
        event={event}
        selectedGroupId={selectedGroupId}
      />
    ),
    primaryButtonProps: {
      children: t('general:apply'),
      onClick: () => {
        if (event) {
          addEventOrganizerMutation.mutate({
            eventId: event.id,
            userIds: tempSelectedUsers.map(user => user.id),
          });
        } else {
          setSelectedUsers(tempSelectedUsers);
          closeMultipleOrganizerDrawer();
        }
      },
      loading: addEventOrganizerMutation.isLoading,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      onClick: () => {
        resetTempSelection();
        closeMultipleOrganizerDrawer();
      },
    },
    onClose: () => {
      resetTempSelection();
      closeMultipleOrganizerDrawer();
    },
    footer: tempSelectedUsers.length > 0 && (
      <Alert
        sx={{ height: 68 }}
        title={t('selected_organizers', { count: tempSelectedUsers.length })}
        severity="info"
        action={{
          text: t('see_collaborators'),
          onClick: () => showSelectedOrganizersDrawer({}),
        }}
      />
    ),
  }));

  const drawerElements = (
    <>
      {multipleOrganizerDrawer}
      {selectedOrganizersDrawer}
    </>
  );

  return {
    drawerElements,
    showDrawer: () => {
      setTempSelectedUsers(selectedUsers);
      showMultipleOrganizerDrawer({});
    },
    selectedUsers,
    setSelectedUsers,
  };
};
