import {useContext, useContextSection} from '@hooks';
import {context} from '../context';
import {Modal, TabPaneProps, TabsProps} from 'antd';
import {ReactNode} from 'react';
import css from './index.module.css';
import {useStore} from 'zustand';
import {tabStore} from '@stores';
import {useContextMenu, ItemParams} from 'react-contexify';
import {DragEndEvent} from '@dnd-kit/core';
import {arrayMove} from '@dnd-kit/sortable';

export type Tab = {
  key: string;
  label: ReactNode;
} & Omit<TabPaneProps, 'tab'>;

export function useTabItems() {
  const {host} = location;

  const tabs = useContextSection(context, function ([tabs]) {
    return tabs.map<Tab>(function (tab) {
      return {
        ...tab,
        originalTab: tab,
        forceRender: true,
        closable: tab.key !== '-1',
        animated: true,
        children: (
          <iframe
            src={`http://${host}${tab.url}`}
            className={css.iframe}
            data-url={tab.url}
          />
        ),
      };
    });
  });
  const [originalTab, dispatch] = useContext(context);

  function onDragEnd({active, over}: DragEndEvent) {
    if (!over) return;

    const {id: fromId} = active,
      {id: toId} = over;
    const fromIdx = originalTab.findIndex(val => val.key === fromId),
      toIdx = originalTab.findIndex(val => val.key === toId);

    dispatch({
      type: 'SORT',
      payload: arrayMove(originalTab, fromIdx, toIdx),
    });
  }

  return [tabs, onDragEnd] as const;
}

export function useTabActive() {
  const dispatch = useContextSection(context, state => state[1]);
  const {key: activeKey, dispatch: setActiveKey} = useStore(tabStore);

  function onClear() {
    Modal.confirm({
      title: '清除标签页',
      content: '你确定要关闭所有标签页吗？',
      onOk() {
        dispatch({type: 'CLEAR'});
      },
    });
  }

  const onEdit: TabsProps['onEdit'] = function (target, action) {
    if (action === 'remove' && typeof target === 'string') {
      dispatch({type: 'REMOVE', payload: target});
    }
  };

  return [activeKey, {onChange: setActiveKey, onClear, onEdit}] as const;
}

export function useMenu() {
  const {show} = useContextMenu({id: 'content_menu'});
  const dispatch = useContextSection(context, state => state[1]);

  function onMenuitemClick(e: ItemParams<{key: string}, any>) {
    const {props, id} = e;
    if (!id || !props?.key) return;
    const {key} = props;
    switch (id) {
      case 'clear':
        dispatch({type: 'CLEAR'});
        break;
      case 'remove':
        dispatch({type: 'REMOVE', payload: key});
        break;
      case 'remove_other':
        dispatch({type: 'REMOVE_OTHER', payload: key});
        break;
      case 'remove_right':
        dispatch({type: 'REMOVE_RIGHT', payload: key});
        break;
    }
  }

  return {show, onMenuitemClick};
}
