import React, { ReactNode } from 'react';
import classNames from 'clsx';
import { TreeItem as MuiTreeItem } from '@mui/x-tree-view';
import { KeyboardArrowDownRounded, KeyboardArrowRightRounded } from '@mui/icons-material';

import { autoSuggestHighlight } from '@/mui/helpers';

import Checkbox from '../Checkbox/Checkbox';
import Stack from '../Stack/Stack';
import Typography from '../Typography/Typography';

import styles from './TreeViewItem.module.scss';

type Props = {
  autoSuggest: boolean;
  searchText: string;
  label: string;
  id?: string;
  highlight?: string;
  itemId: string;
  disabled?: boolean;
  multiSelect: boolean;
  selected: boolean;
  indeterminate: boolean;
  children: ReactNode;
  onNodeSelect: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  onNodeExpand: (event: React.MouseEvent<SVGSVGElement, MouseEvent>, itemId: string, isExpand: boolean) => void;
};

// todo: fixme
function TreeItem({
  autoSuggest,
  searchText,
  label,
  id,
  highlight,
  itemId,
  disabled,
  onNodeExpand,
  multiSelect,
  onNodeSelect,
  selected,
  indeterminate,
  children,
}: Props) {
  const childNodes = autoSuggest
    ? autoSuggestHighlight(searchText, label)
    : [
        {
          id,
          text: label,
          highlight,
        },
      ];

  return (
    <MuiTreeItem
      itemId={itemId}
      disabled={disabled}
      slots={{
        expandIcon: () => <KeyboardArrowRightRounded onClick={(event) => onNodeExpand(event, itemId, true)} />,
        collapseIcon: () => <KeyboardArrowDownRounded onClick={(event) => onNodeExpand(event, itemId, false)} />,
      }}
      label={
        <Stack
          direction="row"
          alignItems="center"
          className={classNames(styles.TreeItemLabel, {
            [styles.TreeItemLabel___multiSelect]: multiSelect,
          })}
          onClick={onNodeSelect}
        >
          {multiSelect && <Checkbox checked={selected} indeterminate={!selected && indeterminate} />}
          <div>
            {childNodes.map((node) => (
              <Typography key={node.id} variant="body2" component="span" fontWeight={node.highlight ? 600 : 400}>
                {node.text}
              </Typography>
            ))}
          </div>
        </Stack>
      }
    >
      {children}
    </MuiTreeItem>
  );
}

TreeItem.displayName = 'TreeItem';

export default TreeItem;
