import React, { useCallback } from 'react';
import { useTranslations } from '@wix/patterns-fields';
import type { CellViewProps } from '../../types';
import { formatDatePart, formatTimePart } from './formatters';
import { isValidDate } from './helpers';
import { useSubCellClickTracker, type SubCell } from './subCellContext';
import { classes } from './View.st.css.js';

export const DateTimeView: React.FC<CellViewProps<Date | null>> = ({
  value,
}) => {
  const { t } = useTranslations();
  const tracker = useSubCellClickTracker();

  const recordClick = useCallback(
    (sub: SubCell) => () => tracker.record(sub),
    [tracker],
  );

  if (!isValidDate(value)) {
    return (
      <span className={classes.placeholder}>
        {t('CMS.cellDateTime.placeholder')}
      </span>
    );
  }

  return (
    <>
      <span
        data-sub-cell="date"
        className={classes.datePart}
        onMouseDownCapture={recordClick('date')}
      >
        {formatDatePart(value)}
      </span>
      <span aria-hidden className={classes.divider} />
      <span
        data-sub-cell="time"
        className={classes.timePart}
        onMouseDownCapture={recordClick('time')}
      >
        {formatTimePart(value)}
      </span>
    </>
  );
};
