import { Checkbox, Transfer } from 'antd';
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
  arrayMove,
} from 'react-sortable-hoc';
import style from './style.module.scss'

import type { Tagging } from 'api';
import type { TransferItem, TransferProps } from 'antd/es/transfer';
import type { ReactElement } from 'react';

const Layout = ({children}: {children: any}) => <ul className={style['tagging-transfer']}>{children}</ul>;

type ItemProps = { value: Tagging, checked: boolean, onChange: (checked: boolean) => void, append?: ReactElement, showIndex: number }
const Item = ({ value, append, checked, onChange, showIndex }: ItemProps) => {
  return (
    <li className={style['sort-item'] + ' ' + (append ? style["sort-bar-parent"] : '')}>
      <span>{ showIndex + 1 }. </span>
      <Checkbox checked={checked} onChange={(e) => onChange(e.target.checked)}>
        {value.tagTitle}
      </Checkbox>
      { append && <span className={style['sort-bar']} children={append} /> }
    </li>
  )
}

const SortLayout = SortableContainer(Layout)
const SortDrag = SortableHandle(() => <i className="iconfont icon-order" />);
const SortItem = SortableElement((props: Omit<ItemProps, 'append'>) => <Item {...props} append={<SortDrag />} />)


interface DataType {
  key: string;
  data: Tagging
}

interface TableTransferProps extends TransferProps<TransferItem & DataType> {
  dataSource: DataType[];
  onChangeSort?: (data: DataType[]) => void
}


// Customize Table Transfer
export const SortTransfer = ({ onChangeSort, ...restProps }: TableTransferProps) => (
  <Transfer {...restProps}>
    {({
      direction,
      filteredItems,
      onItemSelect,
      selectedKeys: listSelectedKeys,
    }) => {
      const SLayout = direction === 'left' ? Layout : SortLayout
      const SItem = direction === 'left' ? Item : SortItem
      return (
        <SLayout
          onSortEnd={(data) => onChangeSort && onChangeSort(arrayMove(filteredItems, data.oldIndex, data.newIndex))}
          useDragHandle
          children={
            filteredItems.map((item, index) => (
              <SItem 
                value={item.data} 
                key={item.data.tagId} 
                index={index} 
                showIndex={index}
                checked={listSelectedKeys.some(key => key === item.key)}
                onChange={(check) => onItemSelect(item.key, check)}
              />
            ))
          }
        />
      )
    }}
  </Transfer>
);