import React, { useCallback, useEffect, useRef } from 'react';
import type { InputArea } from '@wix/design-system';
import { Box } from '@wix/design-system';
import { CellJsonInput } from '@wix/patterns-fields';
import type { CellEditProps } from '../../types';
import { classes } from './Edit.st.css.js';

export const ObjectEdit: React.FC<CellEditProps<Record<string, unknown>>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
  inputRef,
}) => {
  const committedRef = useRef(false);
  const inputAreaRef = useRef<InputArea | null>(null);

  // Expand to fit content immediately on mount (= entering edit mode).
  // Deferred to next frame so the textarea has rendered its content.
  useEffect(() => {
    requestAnimationFrame(() => {
      inputAreaRef.current?.calculateComputedRows();
    });
  }, []);

  const handleChange = useCallback(
    (parsed?: any) => {
      onChange(parsed as Record<string, unknown>);
    },
    [onChange],
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        committedRef.current = true;
        onCancel();
      }
      // Enter is not handled — multi-line JSON needs Enter for newlines
    },
    [onCancel],
  );

  const handleBlur = useCallback(() => {
    if (!committedRef.current) {
      onCommit();
    }
  }, [onCommit]);

  return (
    <Box width="100%" height="100%">
      <CellJsonInput
        ref={(instance: any) => {
          inputAreaRef.current = instance;
          if (inputRef) {
            inputRef.current = instance;
          }
        }}
        size="small"
        value={value}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        autoSelect={false}
        autoGrow
        minRowsAutoGrow={1}
        className={classes.jsonInput}
      />
    </Box>
  );
};
