import { type FC, useEffect, useMemo, useState } from 'react';

import { IconTrash } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import HuDrawer from '@material-hu/components/design-system/Drawer';
import HuSearch from '@material-hu/components/design-system/Inputs/Search';
import HuList from '@material-hu/components/design-system/List';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullname, getInitials } from 'src/utils/userUtils';

type Props = {
  open: boolean;
  onClose: () => void;
  agents: User[];
  title?: string;
  onDelete?: (agentId: number) => void;
  showSearch?: boolean;
  showCount?: boolean;
  countLabel?: string;
};

const AgentListDrawer: FC<Props> = ({
  open,
  onClose,
  agents,
  title,
  onDelete,
  showSearch = false,
  showCount = false,
  countLabel,
}) => {
  const { t } = useLokaliseTranslation(['service_management', 'general']);
  const [search, setSearch] = useState('');

  const filteredAgents = useMemo(() => {
    if (!search) return agents;
    const lowerSearch = search.toLowerCase();
    return agents.filter(agent =>
      getFullname(agent).toLowerCase().includes(lowerSearch),
    );
  }, [agents, search]);

  const handleClose = () => {
    setSearch('');
    onClose();
  };

  useEffect(() => {
    if (!open) {
      setSearch('');
    }
  }, [open]);

  if (!agents || agents.length === 0) {
    return null;
  }

  return (
    <HuDrawer
      open={open}
      onClose={handleClose}
      hasBackButton
      title={title || t('selected_coordinators_title')}
    >
      <CardContainer
        fullWidth
        padding={0}
        color="grey"
        sx={{
          border: 'none',
          pb: filteredAgents.length > 0 ? 0 : 2,
        }}
      >
        <Stack>
          {showSearch && (
            <HuSearch
              value={search}
              onChange={value => setSearch(value)}
              sx={{ p: 2 }}
            />
          )}
          {showCount && (
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              sx={{
                color: theme => theme.palette.new.text.neutral,
                px: 2,
              }}
            >
              {countLabel || t('total_agents', { count: agents.length })}
            </Typography>
          )}
          {filteredAgents.length === 0 && search && (
            <Typography
              variant="globalS"
              sx={{
                color: theme => theme.palette.new.text.neutral,
                p: 2,
              }}
            >
              {t('agent_autocomplete_no_results_title')}
            </Typography>
          )}
          {filteredAgents.length > 0 && (
            <HuList sx={{ backgroundColor: 'transparent' }}>
              {filteredAgents.map((agent, index) => (
                <HuListItem
                  key={agent.id}
                  avatar={{
                    src: agent.profilePicture || undefined,
                    text: getInitials(getFullname(agent)),
                  }}
                  text={{
                    title: getFullname(agent),
                  }}
                  divider={index !== filteredAgents.length - 1}
                  action={
                    onDelete && {
                      Icon: IconTrash,
                      onClick: () => onDelete(agent.id),
                    }
                  }
                />
              ))}
            </HuList>
          )}
        </Stack>
      </CardContainer>
    </HuDrawer>
  );
};

export default AgentListDrawer;
