import React from "react";
import { TimeSelect } from "./TimeSelect";
import { TimePickerProps } from "./TimeProps";
import {
  getValidTimeValue,
  genShowHourMinuteSecond,
  getHourMinuteSecond,
  getDisabledHours,
  getDisabledMinutes,
  getDisabledSeconds,
  getDisabledMilliseconds,
} from "./util";
import { DateChangeContext } from "../calendar/DateProps";

type SelectType = "hour" | "minute" | "second" | "milliseconds";

export function Combobox({
  value: _value,
  onChange,
  format = "HH:mm:ss",
  ...props
}: Partial<TimePickerProps>) {
  const value = getValidTimeValue(_value, props, format);

  const {
    showHour,
    showMinute,
    showSecond,
    showMilliseconds,
  } = genShowHourMinuteSecond(format);
  const {
    hour = null,
    minute = null,
    second = null,
    milliseconds = null,
  } = _value ? getHourMinuteSecond(value) : {};

  const handleItemChange = (type: SelectType) => (
    selectValue: number,
    context: DateChangeContext
  ): void => {
    const newValue = value.clone();
    switch (type) {
      case "hour":
        newValue.hour(selectValue);
        break;
      case "minute":
        newValue.minute(selectValue);
        break;
      case "second":
        newValue.second(selectValue);
        break;
      case "milliseconds":
        newValue.milliseconds(selectValue);
        break;
    }
    onChange(getValidTimeValue(newValue, props, format), context);
  };

  const {
    hourStep = 1,
    minuteStep = 1,
    secondStep = 1,
    millisecondsStep = 1,
  } = props;

  return (
    <>
      {showHour && (
        <TimeSelect
          value={hour}
          to={23}
          step={hourStep}
          disabledValues={getDisabledHours(props)}
          onChange={handleItemChange("hour")}
        />
      )}
      {showMinute && (
        <TimeSelect
          value={minute}
          to={59}
          step={minuteStep}
          disabledValues={getDisabledMinutes(hour, props)}
          onChange={handleItemChange("minute")}
        />
      )}
      {showSecond && (
        <TimeSelect
          value={second}
          to={59}
          step={secondStep}
          disabledValues={getDisabledSeconds(hour, minute, props)}
          onChange={handleItemChange("second")}
        />
      )}
      {showMilliseconds && (
        <TimeSelect
          value={milliseconds}
          to={999}
          step={millisecondsStep}
          disabledValues={getDisabledMilliseconds(hour, minute, second, props)}
          onChange={handleItemChange("milliseconds")}
        />
      )}
    </>
  );
}

Combobox.displayName = "TimePickerCombobox";
