import { memo, useCallback } from 'react';

import CheckboxBase from '@design-system/Checkbox/CheckboxBase';
import RadioBase from '@design-system/RadioButton/RadioBase';
import ListItemButton, {
  type ListItemButtonProps,
} from '@mui/material/ListItemButton';
import { appearFromBottom } from '@utils/animations';

export type SelectableListItemProps = {
  children: React.ReactNode;
  disabled?: boolean;
  id: string;
  /** Checkbox indeterminate state. Only applies when `variant` is `"multiple"` (default). */
  indeterminate?: boolean;
  onSelect: (id: string) => void;
  selected: boolean;
  /**
   * Whether to show the selection indicator (checkbox or radio).
   * Legacy name kept for API compatibility.
   */
  showCheckbox?: boolean;
  /** `"multiple"` renders a checkbox; `"single"` renders a radio. Defaults to `"multiple"`. */
  variant?: 'single' | 'multiple';
  style?: React.CSSProperties;
} & Omit<ListItemButtonProps, 'onSelect'>;

const SelectableListItem = memo(
  ({
    children,
    disabled,
    id,
    indeterminate,
    onSelect,
    selected,
    showCheckbox = true,
    sx,
    variant = 'multiple',
    ...props
  }: SelectableListItemProps) => {
    const handleSelect = useCallback(() => {
      onSelect(id);
    }, [onSelect, id]);

    return (
      <ListItemButton
        {...props}
        disabled={disabled}
        onClick={handleSelect}
        selected={selected}
        sx={{
          py: 0,
          flexDirection: 'row',
          alignItems: 'center',
          gap: 1.25,
          animation: `${appearFromBottom} 125ms ease-in-out backwards`,
          transition:
            'background-color 125ms ease-in-out, opacity 125ms ease-in-out',
          '&.Mui-selected': {
            '&:hover,&:focus-visible': {
              backgroundColor: theme =>
                theme.palette.new.action.background.neutral.hover,
            },
            backgroundColor: 'transparent',
          },
          '&:hover,&:focus-visible': {
            backgroundColor: theme =>
              theme.palette.new.action.background.neutral.hover,
          },
          ...sx,
        }}
      >
        {showCheckbox &&
          (variant === 'multiple' ? (
            <CheckboxBase
              checked={selected || false}
              indeterminate={indeterminate}
              tabIndex={-1}
            />
          ) : (
            <RadioBase
              checked={selected || false}
              tabIndex={-1}
            />
          ))}
        {children}
      </ListItemButton>
    );
  },
);

SelectableListItem.displayName = 'SelectableListItem';

export default SelectableListItem;
