import * as React from "react";
import TreeView, { EventCallback, IBranchProps, INode, LeafProps, flattenTree } from "react-accessible-treeview";
import { IFlatMetadata } from "react-accessible-treeview/dist/TreeView/utils";
import { CallBackEventTarget } from "../../../../../core/extensions/extensions";
import "./styles.css";
import { CoreText, CoreTextType } from "../../../../../core/ui/text/text";
import { themeStore } from "../../../../..";

export interface ISkillView {
  name: string;
  children?: ISkillView[];
  isSystem?: boolean;
  id?: string;
  interface?: string;
  out?: string;
}
export interface ISkillTreeProps {
  skills: ISkillView;
  dragEnd: CallBackEventTarget;
}

interface IRefListerProps {
  element: INode<IFlatMetadata>;
  getNodeProps: (args?: { onClick?: EventCallback }) => IBranchProps | LeafProps;
  handleExpand: EventCallback;
  handleSelect: EventCallback;
  dragEnd: CallBackEventTarget;
  isBranch: boolean;
  style: React.CSSProperties;
}

export const RefListener = (props: IRefListerProps) => {
  const ref = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    if (ref.current && props.isBranch === false) {
      ref.current.addEventListener("dragend", (e) => {
        // @ts-expect-error
        if (e && e.target && e.target.innerHTML) {
          // @ts-expect-error
          props.dragEnd(e);
        }
      });
    }
  }, [ref, props]);

  return (
    <div style={props.style} {...props.getNodeProps({ onClick: props.handleExpand })}>
      <div
        onClick={(e) => {
          props.handleSelect(e);
        }}
      />

      <div
        ref={ref}
        style={{ color: "black", alignItems: "center", height: "max-content", display: "flex" }}
        draggable={props.isBranch ? undefined : "true"}
      >
        {props.isBranch ? undefined : ""}
        <CoreText text={props.element.name} type={CoreTextType.large} color={themeStore.theme.darkOnSurfaceVariant} />
      </div>
    </div>
  );
};
export const SkillTree = (props: ISkillTreeProps) => {
  return (
    <div className="directory">
      <TreeView
        data={flattenTree(props.skills)}
        aria-label="onSelect"
        onSelect={() => {}}
        multiSelect
        nodeAction="check"
        nodeRenderer={({ element, getNodeProps, handleSelect, handleExpand, isBranch, level }) => {
          return (
            <RefListener
              style={{ paddingLeft: 20 * (level - 1) }}
              isBranch={isBranch}
              dragEnd={props.dragEnd}
              getNodeProps={getNodeProps}
              element={element}
              handleExpand={handleExpand}
              handleSelect={handleSelect}
            />
          );
        }}
      />
    </div>
  );
};
