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

type ColorInputRef = React.MutableRefObject<
  InputImperativeActions | null | undefined
>;

/**
 * ColorEdit bridges @wix/patterns-fields CellColorInput with the EditableTable
 * cell framework.
 *
 * The ColorPicker popover steals focus when opened — a naive blur→commit
 * handler would close the cell while the picker is still open. We RAF after
 * blur and skip commit when the post-blur active element is inside the WDS
 * ColorPicker ([role="group"][aria-label="Color picker"]) or the CellColorInput's
 * own popover (kept inside wrapperRef).
 */
export const ColorEdit: React.FC<CellEditProps<string | undefined>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
  inputRef,
}) => {
  const wrapperRef = useRef<HTMLDivElement | null>(null);
  const colorInputRef = inputRef as ColorInputRef;

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

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        onCommit();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onCancel();
      }
    },
    [onCommit, onCancel],
  );

  const handleBlur = useCallback(() => {
    requestAnimationFrame(() => {
      const active = document.activeElement as HTMLElement | null;
      if (
        active &&
        active.closest('[role="group"][aria-label="Color picker"]')
      ) {
        return;
      }
      if (active && wrapperRef.current?.contains(active)) {
        return;
      }
      onCommit();
    });
  }, [onCommit]);

  return (
    <div
      ref={wrapperRef}
      onKeyDown={handleKeyDown}
      onBlur={handleBlur}
      onClick={(e) => e.stopPropagation()}
      onMouseDown={(e) => e.stopPropagation()}
      className={classes.root}
    >
      <CellColorInput
        inputRef={colorInputRef}
        value={value ?? ''}
        onChange={onChange}
        size="small"
        border="none"
      />
    </div>
  );
};
