/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import {JSX, useEffect, useState} from 'react';
import {useSelector} from 'react-redux';
import {Moment} from 'moment';
import {AppStore} from 'store';
import {getTimezoneAbbreviation, isoTimeFormat} from 'utility/date';

export const DateComponent = ({
  date,
  className
}: {
  date: Moment;
  className?: string;
}): JSX.Element => {
  const preferredTimeFormat = useSelector((state: AppStore) => state.preferredTimeFormat.timeFormat);
  const isUTC = preferredTimeFormat === 'utc';
  const utcDate = date.isValid() ? date.format(`${isoTimeFormat} UTC`) : '';
  const localDate = date.isValid() ? `${date.clone().local().format(isoTimeFormat)} ${getTimezoneAbbreviation(date.toDate())}` : '';
  const defaultDate = isUTC ? utcDate : localDate;
  const hoverDate = isUTC ? localDate : utcDate;
  const [currentDate, setCurrentDate] = useState(defaultDate);

  useEffect(() => {
    setCurrentDate(defaultDate);
  }, [date, preferredTimeFormat]);

  const onMouseEnter = () => {
    setCurrentDate(hoverDate);
  };

  const onMouseOut = () => {
    setCurrentDate(defaultDate);
  };

  const onBlur = () => {
    setCurrentDate(defaultDate);
  };

  return (
    <p
      onMouseEnter={onMouseEnter}
      onMouseOut={onMouseOut}
      onBlur={onBlur}
      className={className}
    >
      {currentDate}
    </p>
  );
};