import { Node } from "@antv/x6";
import CustomInput from "../CustomInput";
import { LaneItem, StageItem } from "@/types";
import { useEffect, useRef, useState } from "react";

export default function Pool({ 
  node,
  fillContent,
  strokeWidth,
  strokeColor,
 }: { 
  node: Node,
  fillContent: string,
  strokeWidth: number,
  strokeColor: string,
}) {
  const {
    poolName,
    text,
    lane,
    stage,
    direction,
    headerHeight,
    stageWidth,
    laneHeadHeight,
  } = node.getData();

  const size = node.getSize();
  const [control, setControl] = useState();
  const handleStartMove = () => {
    node.setData({
      ignoreDrag: false,
    });
  };

  const handleEndMove = () => {
    node.setData({
      ignoreDrag: true,
    });
  };

  const handleSetControl = (type: "stage" | "lane", index: number) => {

  };

  const dragStart = useRef<{x: number, y: number}>();
  const dragRef = useRef<{ 
    originPosition: {x: number, y: number}, 
    target: string, 
    type: 'x' | 'y',
    el: HTMLDivElement
  }>();

  // TODO 拖拽边框
  // 1.拖拽开始，记录开始位置
  // 记录拖对象、方向、位置
  const handleDragStart = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, target: string, type: 'x' | 'y') => {
    console.log('mouse down', e)
    dragRef.current = {
      originPosition: {x: e.clientX, y: e.clientY},
      el: e.currentTarget,
      target,
      type,
    };
  }

  // 2.拖拽中
  // 更新拖拽对象位置
  const handleDragMove = (e: MouseEvent) => {
    if(dragRef.current) {
      const { originPosition, type, el} = dragRef.current;
      const {clientX, clientY} = e;
      const diffX = clientX - originPosition.x;
      const diffY = clientY - originPosition.y;
    }
  }

  // 3.拖拽结束
  // 更新设置对象
  const handleDragEnd = () => {
    console.log('mouse up', dragStart.current)
    dragRef.current = undefined;
    document.removeEventListener("mouseup", handleDragEnd);
    document.removeEventListener("mousemove", handleDragMove);
  }

  useEffect(() => {
    document.addEventListener("mouseup", handleDragEnd);
    // document.addEventListener("mousemove", handleDragMove);

    return () => {
      document.removeEventListener("mouseup", handleDragEnd);
      document.removeEventListener("mousemove", handleDragMove);
    };
  }, []);

  return direction === "vertical" ? (
    // 垂直泳池
    <>
      <div
        className="w-full relative cursor-move"
        style={{
          height: headerHeight,
          background: fillContent,
          borderBottom: `solid ${strokeWidth}px ${strokeColor}`,
        }}
        onMouseEnter={handleStartMove}
        onMouseLeave={handleEndMove}
      >
        <CustomInput
          value={poolName}
          styles={text}
          node={node}
          onChange={(val) => node.setData({ poolName: val })}
        />
        {/* <div 
          className="absolute w-full bottom-0 h-4px transition hover:bg-#239edd cursor-ns-resize"
          onMouseEnter={handleEndMove}
          onMouseLeave={handleStartMove}
          onMouseDown={(e) => handleDragStart(e, 'headerHeight', 'y')}
        ></div> */}
      </div>
      <div
        className="relative content"
        style={{ height: `calc(100% - ${headerHeight}px)` }}
      >
        {/* 阶段 */}
        {stage.length ? (
          <div className="stage h-full w-full absolute left-0 top-0">
            {stage.map((stageItem: StageItem, index: number) => {
              return (
                <div
                  key={index}
                  style={{
                    width: "100%",
                    height: stageItem.height - strokeWidth,
                    borderBottom:
                      index < stage.length - 1
                        ? `solid ${strokeWidth}px ${strokeColor}`
                        : "node",
                  }}
                >
                  <div
                    className="relative stage-item cursor-move"
                    style={{
                      width: stageWidth,
                      background: fillContent,
                      height: stageItem.height - 2 * strokeWidth,
                      borderRight: `solid ${strokeWidth}px ${strokeColor}`,
                    }}
                    onMouseEnter={handleStartMove}
                    onMouseLeave={handleEndMove}
                    onClick={() => handleSetControl("stage", index)}
                  >
                    <CustomInput
                      value={stageItem.name}
                      styles={text}
                      node={node}
                      txtStyle={{
                        transform: `rotate(-90deg) translateX(-${stageItem.height}px)`,
                        transformOrigin: "0 0",
                        height: stageWidth,
                        width: stageItem.height,
                      }}
                      onChange={(val) => {
                        node.setData({
                          stage: stage.map((item: StageItem, i: number) => {
                            if (index === i) {
                              return {
                                ...item,
                                name: val,
                              };
                            }
                          }),
                        });
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          ""
        )}
        {/* 泳道 */}
        <div
          className="lane flex h-full absolute top-0"
          style={{ left: stage.length ? stageWidth : 0 }}
        >
          {lane.map((item: any, index: number) => (
            <div
              key={index}
              style={{
                width: item.width,
                borderRight:
                  index === lane.length - 1
                    ? "none"
                    : `solid ${strokeWidth}px ${strokeColor}`,
              }}
            >
              <div
                className="flex-1 w-full relative cursor-move"
                style={{
                  height: laneHeadHeight,
                  background: fillContent,
                  borderBottom: `solid ${strokeWidth}px ${strokeColor}`,
                }}
                onMouseEnter={handleStartMove}
                onMouseLeave={handleEndMove}
                onClick={() => handleSetControl("lane", index)}
              >
                <CustomInput
                  value={item.name}
                  styles={text}
                  node={node}
                  onChange={(val) => {
                    node.setData({
                      lane: lane.map((item: LaneItem, i: number) => {
                        if (index === i) {
                          return {
                            ...item,
                            name: val,
                          };
                        }
                        return item;
                      }),
                    });
                  }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  ) : (
    // 水平泳池
    <>
      <div
        className="h-full relative cursor-move inline-block"
        style={{
          width: headerHeight,
          background: fillContent,
          borderRight: `solid ${strokeWidth}px ${strokeColor}`,
        }}
        onMouseEnter={handleStartMove}
        onMouseLeave={handleEndMove}
      >
        <CustomInput
          value={poolName}
          styles={text}
          node={node}
          onChange={(val) => node.setData({ poolName: val })}
          txtStyle={{
            transform: `rotate(-90deg) translateX(-${size.height}px)`,
            transformOrigin: "0 0",
            width: size.height,
            height: headerHeight,
          }}
        />
      </div>
      <div
        className="relative content h-full inline-block"
        style={{ width: `calc(100% - ${headerHeight}px)` }}
      >
        {/* 阶段 */}
        {stage.length ? (
          <div className="stage h-full w-full absolute top-0 left-0 flex">
            {stage.map((stageItem: StageItem, index: number) => {
              return (
                <div
                  key={index}
                  style={{
                    width: stageItem.height - strokeWidth,
                    height: "100%",
                    borderRight:
                      index < stage.length - 1
                        ? `solid ${strokeWidth}px ${strokeColor}`
                        : "node",
                  }}
                >
                  <div
                    className="relative stage-item cursor-move"
                    style={{
                      width: stageItem.height - 2 * strokeWidth,
                      background: fillContent,
                      height: stageWidth,
                      borderBottom: `solid ${strokeWidth}px ${strokeColor}`,
                    }}
                    onMouseEnter={handleStartMove}
                    onMouseLeave={handleEndMove}
                  >
                    <CustomInput
                      value={stageItem.name}
                      styles={text}
                      node={node}
                      onChange={(val) => {
                        node.setData({
                          stage: stage.map((item: StageItem, i: number) => {
                            if (index === i) {
                              return {
                                ...item,
                                name: val,
                              };
                            }
                          }),
                        });
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          ""
        )}
        {/* 泳道 */}
        <div
          className="lane absolute left-0"
          style={{
            top: stage.length ? stageWidth : 0,
            width: `100%`,
            height: `calc(100% - ${stage.length ? stageWidth : 0}px)`,
          }}
        >
          {lane.map((item: LaneItem, index: number) => (
            <div
              key={index}
              style={{
                width: "100%",
                height: item.width,
                borderBottom:
                  index === lane.length - 1
                    ? "none"
                    : `solid ${strokeWidth}px ${strokeColor}`,
              }}
            >
              <div
                className="flex-1 w-full relative cursor-move"
                style={{
                  width: laneHeadHeight,
                  height: "100%",
                  background: fillContent,
                  borderRight: `solid ${strokeWidth}px ${strokeColor}`,
                }}
                onMouseEnter={handleStartMove}
                onMouseLeave={handleEndMove}
              >
                <CustomInput
                  value={item.name}
                  styles={text}
                  node={node}
                  txtStyle={{
                    transform: `rotate(-90deg) translateX(-${item.width}px)`,
                    transformOrigin: "0 0",
                    width: item.width - strokeWidth,
                    height: laneHeadHeight,
                  }}
                  onChange={(val) => {
                    node.setData({
                      lane: lane.map((item: LaneItem, i: number) => {
                        if (index === i) {
                          return {
                            ...item,
                            name: val,
                          };
                        }
                        return item;
                      }),
                    });
                  }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}
