import React, { useState } from "react";
import moment, { Moment } from "moment";
import CalendarPart from "./CalendarPart";
import { StyledProps } from "../_type";
import { ControlledProps, useDefaultValue } from "../form/controlled";
import { CalendarTable } from "./CalendarTable";
import { RangeDateType, CalendarTableType } from "./DateProps";
import { useTranslation } from "../i18n";
import { mergeEventProps } from "../_util/merge-event-props";

export interface CalendarProps extends ControlledProps<Moment>, StyledProps {
  /**
   * 允许选择的日期范围，可同时使用 `disabledDate` 实现更精细控制
   */
  range?: RangeDateType;

  /**
   * 可选的日期范围
   */
  disabledDate?: (date: Moment) => boolean;
}

export const Calendar = React.forwardRef(function Calendar(
  props: CalendarProps,
  ref: React.Ref<HTMLDivElement>
) {
  useTranslation(moment);

  const { className, style, ...restProps } = useDefaultValue(props);

  const [type, setType] = useState<CalendarTableType>("date");
  const { value } = props;
  const [curViewMoment, setCurViewMoment] = useState<Moment>(
    moment.isMoment(value) ? value : moment()
  );

  return (
    <CalendarPart.Panel
      ref={ref}
      className={className}
      style={style}
      {...mergeEventProps(props)}
    >
      <CalendarPart.Body>
        <CalendarTable
          {...restProps}
          curViewMoment={curViewMoment}
          onCurViewMomentChange={setCurViewMoment}
          type={type}
          onTypeChange={setType}
        />
      </CalendarPart.Body>
    </CalendarPart.Panel>
  );
});

Calendar.displayName = "Calendar";
