import {tabStore} from '@stores';
import css from './index.module.css';
import {FC} from 'react';
import {useStore} from 'zustand';
import classNames from 'classnames';
import {useSortable} from '@dnd-kit/sortable';
import {ShowContextMenuParams} from 'react-contexify';

type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> &
  Partial<Pick<Type, Key>>;

type Props = {
  id: string;
  label: string;
  onContentMenu: (
    params: MakeOptional<ShowContextMenuParams<unknown>, 'id'>,
  ) => void;
};

const TabItem: FC<Props> = function ({id, label, onContentMenu}) {
  const {key: activeKey, dispatch} = useStore(tabStore);
  const {setNodeRef, transform, transition, attributes, listeners} =
    useSortable({id, attributes: {role: 'tab'}});

  return (
    <li
      onContextMenu={e =>
        id === '-1'
          ? e.preventDefault()
          : onContentMenu({event: e, props: {key: id}})
      }
      id={`p_tab_item_${id}`}
      data-key={id}
      data-isactive={id === activeKey ? '1' : '0'}
      className={classNames(css.tabItem, {
        [css.tabItemActive]: id === activeKey,
      })}
      onClick={() => dispatch(id)}
      ref={setNodeRef}
      {...attributes}
      {...listeners}
      style={{
        transition,
        transform: `translate3d(${transform?.x ?? 0}px, ${
          transform?.y ?? 0
        }px, 0)`,
      }}
    >
      {label}
    </li>
  );
};

export default TabItem;
