import React from "react";
import moment, { Moment } from "moment";
import CalendarPart from "../calendar/CalendarPart";
import { Button } from "../button";
import { CommonDatePickerProps } from "./DatePickerProps";
import { useTranslation } from "../i18n";
import {
  CalendarTableType,
  showTimeType,
  RangeDateType,
} from "../calendar/DateProps";
import { CalendarTableProps } from "../calendar/CalendarTable";
import { Omit } from "../_type";
import { useConfig } from "../_util/config-context";

interface CalendarWrapperProps extends CommonDatePickerProps {
  /**
   * Render Props
   */
  children: (props: any) => React.ReactNode;

  /**
   * 确定回调
   */
  onOk?: (event: React.MouseEvent) => void;

  /**
   * 当前展示的日历类型
   */
  type?: CalendarTableType | [CalendarTableType, CalendarTableType];

  /**
   * 日历类型改变回调
   */
  onTypeChange?: (
    types: CalendarTableType | [CalendarTableType, CalendarTableType]
  ) => void;

  /**
   * 是否开启时间选择
   */
  showTime?: showTimeType<Moment | RangeDateType>;
}

function hasValue(value) {
  if (Array.isArray(value)) {
    return moment.isMoment(value[0]) && moment.isMoment(value[1]);
  }
  return moment.isMoment(value);
}

export function CalendarWrapper({
  onOk,
  children,
  ...props
}: CalendarWrapperProps & Omit<CalendarTableProps, "type">) {
  const t = useTranslation();
  const { classPrefix } = useConfig();

  const { value, type, onTypeChange, showTime } = props;

  if (!showTime) {
    return <CalendarPart.Body>{children(props)}</CalendarPart.Body>;
  }

  function setType(value: CalendarTableType) {
    if (Array.isArray(type)) {
      onTypeChange([value, value]);
      return;
    }
    onTypeChange(value);
  }

  function isTimeType() {
    if (Array.isArray(type)) {
      return type[0] === "time" && type[1] === "time";
    }
    return type === "time";
  }

  return (
    <>
      <CalendarPart.Body>{children(props)}</CalendarPart.Body>
      <CalendarPart.Footer
        left={
          <div className={`${classPrefix}-date-status`}>
            {isTimeType() ? (
              <Button
                type="link"
                htmlType="button"
                onClick={() => setType("date")}
                style={{ textDecoration: "none" }}
              >
                {t.selectDate}
              </Button>
            ) : (
              <Button
                type="link"
                htmlType="button"
                onClick={() => setType("time")}
                disabled={!hasValue(value)}
                style={{ textDecoration: "none" }}
              >
                {t.selectTime}
              </Button>
            )}
          </div>
        }
        right={
          <Button
            type="primary"
            htmlType="button"
            onClick={onOk}
            disabled={!hasValue(value)}
          >
            {t.okText}
          </Button>
        }
      />
    </>
  );
}

CalendarWrapper.displayName = "CalendarWrapper";
