import React, { useEffect, useMemo, useRef } from "react";
import { Input, InputRef } from "antd";
import { Node } from "@antv/x6";
import { useSafeState } from "ahooks";
export default function CustomInput(props: {
  value: string;
  styles: React.CSSProperties & {
    textVAlign: 'top' | 'middle' | 'bottom';
    bold: boolean;
    italic: boolean;
  };
  node: Node;
  placeholder?: string;
  txtStyle?: React.CSSProperties;
  onChange?: (value: string) => void;
}) {
  const { value, styles, node, placeholder, txtStyle } = props;
  const [isEditing, setIsEditing] = useSafeState(false);
  const inputRef = useRef<InputRef>(null);
  
  const style = useMemo(() => {
    const top = styles.textVAlign === 'top' ? 0 : styles.textVAlign === 'middle' ? '50%' : undefined;
    const bottom = styles.textVAlign === 'bottom' ? 0 : undefined;
    return {
      ...styles,
      fontWeight: styles.bold ? 'bold' : undefined,
      fontStyle: styles.italic ? 'italic' : undefined,
      transform: styles.textVAlign === 'middle' ? 'translateY(-50%)' : undefined,
      minHeight: '12px',
      top,
      bottom,
    }
  }, [styles]);

  const handleChange = (val: string) => {
    node.setData({ label: val });
    props.onChange?.(val);
  }

  const handleSetEditing = (edit: boolean) => {
    if(node.data?.lock) {
      return
    }
    node.setData({
      ignoreDrag: edit
    })
    if(edit) {
      setTimeout(() => {
        inputRef.current?.focus({ cursor: 'all' });
      }, 100)
    }
    setIsEditing(edit);
  }

  // useEffect(() => {
  //   // 处理字体加载
  //   // @ts-ignore
  //   // WebFont.load({
  //   //   google: {
  //   //     families: [styles.fontFamily]
  //   //   }
  //   // })
  // }, [styles.fontFamily]);

  return (
    <div className="absolute w-full h-full w-full" style={txtStyle}>
      {isEditing ? (
        <Input.TextArea
          ref={inputRef}
          placeholder={placeholder}
          value={value}
          variant="borderless"
          className="absolute"
          style={style}
          onChange={(e) => handleChange(e.target.value)}
          onBlur={() => handleSetEditing(false)}
          autoSize
        />
     ) : (
        <div
          className="absolute w-full"
          style={style}
          onDoubleClick={() => handleSetEditing(true)}
        >
          {value}
        </div>
      )}
    </div>
  );
}
