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 } from './types';

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

  const items = isArray ? (field.value as string[]) : [];
  // biome-ignore lint/correctness/useExhaustiveDependencies: items never change
  const filteredItems = useMemo(() => {
    return items.filter((item: string) =>
      item.toString().toLowerCase().includes(search.toLowerCase()),
    );
  }, [search]);

  const { openDrawer, closeDrawer } = useDrawerLayerItem(id, {
    title: isArray ? texts.items_associated_to_field : field.name,
    secondaryButtonProps: {
      children: texts.back,
      onClick: () => closeDrawer(),
      fullWidth: true,
    },
    children: isArray ? (
      <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 }} />}>
          {filteredItems.length === 0 && (
            <Typography
              variant="globalS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.default,
              }}
            >
              {texts.no_items_found}
            </Typography>
          )}
          {filteredItems.map((item, index) => (
            <ListItem
              key={`${item}|${index}`}
              slotProps={{
                container: {
                  sx: {
                    pl: 0,
                    py: 1,
                  },
                },
              }}
              text={{ title: item }}
            />
          ))}
        </Stack>
      </CardContainer>
    ) : (
      <Typography variant="globalS">{String(field.value)}</Typography>
    ),
  });

  return { openDrawer, closeDrawer };
};

export default useProfileDataDrawer;
