import { CloseOutlined } from "@ant-design/icons";
import { Button, Input } from "antd";
import React, {
  forwardRef,
  useImperativeHandle,
  useState,
  useRef,
  useEffect,
} from "react";
import type { DraggableData, DraggableEvent } from "react-draggable";
import Draggable from "react-draggable";

export type FindReplaceModalRef = {
  open: () => void;
};
export default forwardRef(function FindReplaceModal(
  {
    current = 0,
    count = 0,
    onClose,
    onFind,
    onFindNext,
    onFindPrev,
    onReplace,
    onReplaceAll,
    right = 0,
    top = 0
  }: {
    current: number;
    count: number;
    onFind: (text: string) => void;
    onClose: () => void;
    onFindNext: () => void;
    onFindPrev: () => void;
    onReplace: (searchText: string, replaceText: string) => void;
    onReplaceAll: (searchText: string, replaceText: string) => void;
    right: number;
    top: number;
  },
  ref: React.Ref<FindReplaceModalRef>
) {
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(1);
  const [searchText, setSearchText] = useState("");
  const [replaceText, setReplaceText] = useState("");

  useImperativeHandle(ref, () => ({
    open(active = 1) {
      setActive(active);
      setOpen(true);
    },
  }));

  useEffect(() => {
    if (!open) {
      setBounds({
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
      });
      setSearchText("");
      setReplaceText("");
    }
  }, [open]);

  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const draggleRef = useRef<HTMLDivElement>(null);

  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  const handleReplace = () => {
    onReplace?.(searchText, replaceText);
  };

  const handleReplaceAll = () => {
    onReplaceAll?.(searchText, replaceText);
  };

  const handleClose = () => {
    onClose?.();
    setOpen(false);
  };

  const handleChange = (val: string) => {
    setSearchText(val);
    onFind?.(val);
  };

  return (
    <Draggable
      disabled={disabled}
      bounds={bounds}
      nodeRef={draggleRef}
      onStart={(event, uiData) => onStart(event, uiData)}
    >
      <div
        className="w-320px fixed bg-white rounded-md shadow-md z-100 p-10px"
        ref={draggleRef}
        style={{ display: open ? "block" : "none", right, top }}
      >
        <div className="flex items-ctenter px-10px">
          <span
            className="text-14px mr-12px cursor-pointer"
            style={{ color: active === 1 ? "#333" : "#999" }}
            onClick={() => setActive(1)}
          >
            查找
          </span>
          <span
            className="text-14px cursor-pointer"
            style={{ color: active === 2 ? "#333" : "#999" }}
            onClick={() => setActive(2)}
          >
            替换
          </span>
          <div
            className="flex-1 cursor-move"
            onMouseOver={() => disabled && setDisabled(false)}
            onMouseOut={() => setDisabled(true)}
          ></div>
          <Button
            type="text"
            size="small"
            icon={<CloseOutlined />}
            onClick={handleClose}
          />
        </div>
        <div className="flex">
          <Input
            placeholder="查找内容"
            value={searchText}
            onChange={(e) => handleChange(e.target.value)}
            suffix={
              <span>
                {current}/{count}
              </span>
            }
          />
          <Button
            type="text"
            icon={<i className="iconfont icon-xiangzuo1" />}
            disabled={count === 0}
            onClick={() => onFindPrev?.()}
          />
          <Button
            type="text"
            disabled={count === 0}
            icon={<i className="iconfont icon-xiangyou1" />}
            onClick={() => onFindNext?.()}
          />
        </div>
        {active === 2 && (
          <>
            <div>
              <Input
                placeholder="替换内容"
                value={replaceText}
                onChange={(e) => setReplaceText(e.target.value)}
              />
            </div>
            <div className="flex justify-end gap-16px mt-12px">
              <Button
                type="primary"
                size="small"
                disabled={!searchText || !replaceText}
                onClick={handleReplace}
              >
                替换
              </Button>
              <Button
                type="primary"
                size="small"
                disabled={!searchText || !replaceText}
                onClick={handleReplaceAll}
              >
                全部替换
              </Button>
            </div>
          </>
        )}
      </div>
    </Draggable>
  );
});
