import { useId, useMemo } from 'react';
import { FormProvider, useForm, useWatch } from 'react-hook-form';

import CardContainer from '@design-system/CardContainer';
import FormInputSearch from '@design-system/Inputs/Search/form';
import ListItem from '@design-system/List/components/ListItem';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';

import { useDrawerLayerItem } from '../../../layers/Drawers';

import { type Texts, type User } from './types';

const useProfileUsersDrawer = (
  field: {
    name: string;
    value: User[];
  },
  texts: Texts,
) => {
  const id = useId();
  const form = useForm({
    defaultValues: {
      search: '',
    },
  });
  const search = useWatch({ name: 'search', control: form.control });

  // biome-ignore lint/correctness/useExhaustiveDependencies: prop never changes
  const filteredUsers = useMemo(() => {
    return field.value.filter(user =>
      user.name.toLowerCase().includes(search.toLowerCase()),
    );
  }, [search]);

  const drawer = useDrawerLayerItem(id, {
    title: texts.drawer_title,
    secondaryButtonProps: {
      children: texts.back,
      onClick: () => drawer.closeDrawer(),
      fullWidth: true,
    },
    children: (
      <CardContainer
        fullWidth
        sx={{
          backgroundColor: ({ palette }) =>
            palette.new.background.elements.grey,
          overflow: 'auto',
          maxHeight: '100%',
        }}
      >
        <FormProvider {...form}>
          <FormInputSearch name="search" />
        </FormProvider>
        <Typography
          variant="globalS"
          sx={{
            color: ({ palette }) => palette.new.text.neutral.default,
            my: 3,
            display: 'block',
          }}
        >
          {texts.items_total}
        </Typography>
        <Stack divider={<Divider sx={{ my: 1 }} />}>
          {filteredUsers.length === 0 && (
            <Typography
              variant="globalS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.default,
              }}
            >
              {texts.no_items_found}
            </Typography>
          )}
          {filteredUsers.map((user, index) => (
            <ListItem
              key={`${user.name}|${index}`}
              avatar={{ src: user.profilePicture, alt: user.name }}
              slotProps={{
                container: {
                  sx: {
                    pl: 0,
                    py: 1,
                  },
                },
              }}
              text={{ title: user.name }}
            />
          ))}
        </Stack>
      </CardContainer>
    ),
  });

  return { openDrawer: drawer.openDrawer, closeDrawer: drawer.closeDrawer };
};

export default useProfileUsersDrawer;
