import {tabStore} from '@stores';
import css from './index.module.css';
import {FC, MouseEvent} from 'react';
import {useStore} from 'zustand';
import classNames from 'classnames';
import {useSortable} from '@dnd-kit/sortable';
import {ShowContextMenuParams} from 'react-contexify';
import {CloseSmall} from '@icon-park/react';
import {Modal} from 'antd';
import {shallowEqual} from '@utils';

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 {activeKey, setActiveKey} = useStore(
    tabStore,
    function (state) {
      return {activeKey: state.activeKey, setActiveKey: state.setActiveKey};
    },
    shallowEqual,
  );
  const {setNodeRef, transform, transition, attributes, listeners} =
    useSortable({id, attributes: {role: 'tab'}});
  const dispatch = useStore(tabStore, state => state.dispatch);

  function onClose(e: MouseEvent) {
    e.stopPropagation();
    Modal.confirm({
      title: '关闭标签',
      content: `你确定要关闭${label}吗？`,
      onOk() {
        dispatch({type: 'REMOVE', payload: id});
      },
    });
  }

  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={() => setActiveKey(id)}
      ref={setNodeRef}
      {...attributes}
      {...listeners}
      style={{
        transition,
        transform: `translate3d(${transform?.x ?? 0}px, ${
          transform?.y ?? 0
        }px, 0)`,
      }}
    >
      {label}
      {id !== '-1' && (
        <CloseSmall
          theme='outline'
          size='14'
          fill={id === activeKey ? 'var(--primary-color)' : '#ccc'}
          onClick={onClose}
          className={css.close}
        />
      )}
    </li>
  );
};

export default TabItem;
