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

function isValidDate(value: Date | string | null | undefined): boolean {
  if (!value) {
    return true;
  }
  const date = value instanceof Date ? value : new Date(value);
  return !isNaN(date.getTime());
}

export const DateEdit: React.FC<CellEditProps<Date | string | null>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
  inputRef,
  editTrigger,
}) => {
  const datePickerRef = useRef<DatePicker | null>(null);
  const validDate = isValidDate(value);

  // Auto-open calendar when entering edit mode via type-to-edit
  useEffect(() => {
    if (
      editTrigger &&
      typeof editTrigger === 'object' &&
      editTrigger.kind === 'type'
    ) {
      datePickerRef.current?.openCalendar();
    }
  }, [editTrigger]);

  const wrapperRef = useRef<HTMLDivElement | null>(null);
  const closeCalendar = useCallback(
    () => closeDatePickerCalendar(datePickerRef.current),
    [],
  );
  useCloseOnAncestorScroll(wrapperRef, closeCalendar, !!editTrigger);

  const dateValue = value
    ? value instanceof Date
      ? value
      : new Date(value)
    : null;

  const handleChange = useCallback(
    (date: Date) => {
      onChange(date);
      onCommit();
    },
    [onChange, onCommit],
  );

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

  return (
    <div
      ref={wrapperRef}
      onKeyDown={handleKeyDown}
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
      }}
    >
      <DatePicker
        ref={datePickerRef}
        size="small"
        inputProps={{
          border: 'none',
          prefix: <span />,
          ...(validDate
            ? {}
            : { value: typeof value === 'string' ? value : '' }),
          inputRef: (el: HTMLInputElement) => {
            if (inputRef) {
              inputRef.current = el;
            }
          },
        }}
        value={dateValue && !isNaN(dateValue.getTime()) ? dateValue : undefined}
        onChange={handleChange}
        popoverProps={{ appendTo: 'window', moveBy: { y: 4 } }}
        className={classes.dateInput}
      />
    </div>
  );
};
