import { useState, useRef, useEffect } from "react";
import { Input } from "@/components/ui/input";

interface Props {
  value: unknown;
  onSave: (value: string | null) => void;
  onCancel: () => void;
}

export function EditableCell({ value, onSave, onCancel }: Props) {
  const [editValue, setEditValue] = useState(
    value === null ? "" : String(value)
  );
  const [isNull, setIsNull] = useState(value === null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      onSave(isNull ? null : editValue);
    } else if (e.key === "Escape") {
      onCancel();
    }
  };

  return (
    <div className="flex items-center gap-1">
      <Input
        ref={inputRef}
        value={editValue}
        onChange={(e) => {
          setEditValue(e.target.value);
          setIsNull(false);
        }}
        onKeyDown={handleKeyDown}
        onBlur={() => onSave(isNull ? null : editValue)}
        className="h-6 text-xs"
        disabled={isNull}
      />
      <button
        className={`shrink-0 rounded px-1 text-[10px] ${
          isNull
            ? "bg-muted text-muted-foreground"
            : "text-muted-foreground hover:bg-muted"
        }`}
        onClick={() => {
          setIsNull(!isNull);
          if (!isNull) {
            setEditValue("");
          }
        }}
        onMouseDown={(e) => e.preventDefault()}
      >
        NULL
      </button>
    </div>
  );
}
