import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  CellTimeInput,
  TimeView as FieldsTimeView,
  type Time,
} from '@wix/patterns-fields';
import type { TimeInputImperativeActions } from '@wix/design-system';
import type { CellEditProps } from '../../types';
import { useCloseOnAncestorScroll } from '../../../../hooks/useCloseOnAncestorScroll';
import { CellViewLayout } from '../CellViewLayout';
import { classes } from './Edit.st.css.js';

export const TimeEdit: React.FC<CellEditProps<Time | null>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
  inputRef,
  editTrigger,
}) => {
  const wrapperRef = useRef<HTMLDivElement | null>(null);
  const timeInputRef = useRef<TimeInputImperativeActions | null>(null);
  const [maskInitialEmpty, setMaskInitialEmpty] = useState(value != null);
  useEffect(() => setMaskInitialEmpty(false), []);

  const closeDropdown = useCallback(() => timeInputRef.current?.blur(), []);
  useCloseOnAncestorScroll(wrapperRef, closeDropdown, !!editTrigger);

  const handleKeyDownCapture = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        onCancel();
      }
    },
    [onCancel],
  );

  return (
    <div
      ref={wrapperRef}
      onKeyDownCapture={handleKeyDownCapture}
      className={classes.wrapper}
    >
      <CellTimeInput
        ref={timeInputRef}
        value={value}
        onChange={onChange}
        onCommit={onCommit}
        inputRef={
          inputRef as React.MutableRefObject<
            HTMLInputElement | null | undefined
          >
        }
        dataHook="time-edit"
      />
      {maskInitialEmpty && value != null && (
        <div aria-hidden className={classes.overlay}>
          <CellViewLayout>
            <FieldsTimeView data={value} />
          </CellViewLayout>
        </div>
      )}
    </div>
  );
};
