import { useEffect, useRef } from "react";

type CellEditorProps = {
  x: number;
  y: number;
  width: number;
  height: number;
  value: string;
  onSave: (text: string) => void;
  onCancel: () => void;
};

const CellEditor = ({ x, y, width, height, value, onSave, onCancel }: CellEditorProps) => {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
    inputRef.current?.select();
  }, []);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      onSave(inputRef.current?.value || "");
    } else if (e.key === "Escape") {
      e.preventDefault();
      onCancel();
    }
  };

  const handleBlur = () => {
    onSave(inputRef.current?.value || "");
  };

  return (
    <div
      style={{
        position: "fixed",
        left: `${x}px`,
        top: `${y}px`,
        width: `${width}px`,
        height: `${height}px`,
        zIndex: 1000,
        pointerEvents: "auto",
      }}
    >
      <input
        ref={inputRef}
        type="text"
        defaultValue={value}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        style={{
          width: "100%",
          height: "100%",
          padding: "4px 8px",
          border: "2px solid #3b82f6",
          borderRadius: "4px",
          fontSize: "14px",
          fontFamily: "Arial",
          textAlign: "center",
          outline: "none",
        }}
      />
    </div>
  );
};

export default CellEditor;

