import { useState } from 'react';

import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';
import { IconSearch } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuInputClassic from '@material-hu/components/design-system/Inputs/Classic';

import { useDebounce } from 'src/hooks/useDebounce';
import { type GetViewersFunction } from 'src/hooks/usePostViewers';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import ViewersList from './ViewersList';

type ViewersListDrawerProps = {
  postId: number;
  getViewers: GetViewersFunction;
  container?: HTMLDivElement | null;
  onViewerCountUpdate?: (count: number) => void;
};

const getViewersListDrawer: GetDrawerConfiguration<ViewersListDrawerProps> = ({
  postId,
  getViewers,
  container,
  onViewerCountUpdate,
  closeDrawer,
}) => {
  const { t } = useTranslation('post');
  const [searchQuery, setSearchQuery] = useState('');
  const { debouncedValue: debouncedSearch } = useDebounce(searchQuery, 500);

  return {
    children: (
      <Stack sx={{ gap: 2 }}>
        <Stack
          sx={{
            borderRadius: theme => theme.shape.borderRadiusL,
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
            p: 2,
            gap: 2,
          }}
        >
          <HuInputClassic
            placeholder={t('search_viewers')}
            value={searchQuery}
            onChange={setSearchQuery}
            hasCounter={false}
            startAdornment={<IconSearch />}
          />
          <ViewersList
            postId={postId}
            getViewers={getViewers}
            searchQuery={debouncedSearch}
            onViewerCountUpdate={onViewerCountUpdate}
          />
        </Stack>
      </Stack>
    ),
    title: t('seen_by'),
    hasCloseButton: true,
    footer: (
      <Button
        onClick={closeDrawer}
        variant="contained"
        size="large"
        fullWidth
      >
        {t('general:accept')}
      </Button>
    ),
    container,
  };
};

export default getViewersListDrawer;
