import React, { useMemo } from 'react';
import { format } from 'date-fns';
import type { SelectRootProps } from '../atoms';
import { Flex, Select } from '../atoms';
import { getTimeOptions } from '../utils';

interface TimeSelectProps extends SelectRootProps {
  maxTime?: Date;
  minTime?: Date;
  time?: Date;
}

const getOptionValue = (date?: Date, timeValue?: Date): string | undefined => {
  if (date && timeValue) {
    if (format(date, 'yyyyMMdd') === format(timeValue, 'yyyyMMdd')) {
      return format(date, 'HH:mm');
    }
  }
};

export function TimeSelect({
  value,
  maxTime,
  minTime,
  time,
  ...rest
}: TimeSelectProps): React.ReactElement {
  const timeOptions = useMemo(() => {
    return getTimeOptions();
  }, []);

  const [minOption, maxOption] = useMemo(() => {
    return [getOptionValue(minTime, time), getOptionValue(maxTime, time)];
  }, [maxTime, minTime, time]);

  return (
    <Select.Root value={value} {...rest}>
      <Flex direction="column" width="100%">
        <Select.Trigger placeholder="-        " style={{ minWidth: '100px' }}>
          {value}
        </Select.Trigger>
      </Flex>
      <Select.Content>
        {timeOptions.map((option) => {
          const visible =
            (!minOption || option >= minOption) &&
            (!maxOption || option <= maxOption);

          if (!visible) {
            return null;
          }
          return (
            <Select.Item key={option} value={option}>
              {option}
            </Select.Item>
          );
        })}
      </Select.Content>
    </Select.Root>
  );
}
