import React, { Ref } from "react";
import classNames from "classnames";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";
import { TimelineItem } from "./TimelineItem";
import { forwardRefWithStatics } from "../_util/forward-ref-with-statics";
import { TimelineContext } from "./TimelineContext";
import { isChildOfType } from "../util";

export interface TimelineProps extends StyledProps {
  /**
   * 时间轴模式
   *
   * - "light" - 轻量样式的时间轴
   * - "vertical" - 垂直时间轴
   * - "vertical-time-left" - 时间展示在左的垂直时间轴
   * - "vertical-alternate" - 左右交替展示的垂直时间轴
   * - "horizontal" - 水平时间轴
   * @default "vertical-light"
   */
  mode?:
    | "light"
    | "vertical"
    | "vertical-time-left"
    | "vertical-alternate"
    | "horizontal";

  /**
   * 是否使用虚线连接
   *
   * @default false
   */
  dashedLine?: boolean;

  /**
   * 尾部渲染内容
   */
  end?: React.ReactNode;

  /**
   * 时间轴节点
   */
  children?: React.ReactNode;
}

export const Timeline = forwardRefWithStatics(
  function Timeline(
    {
      mode = "light",
      dashedLine,
      end,
      className,
      children,
      ...props
    }: TimelineProps,
    ref: Ref<HTMLDivElement>
  ) {
    const { classPrefix } = useConfig();
    return (
      <div
        ref={ref}
        className={classNames(`${classPrefix}-timeline`, className, {
          [`${classPrefix}-timeline--dashline`]: dashedLine,
          [`${classPrefix}-timeline--timeleft`]: mode === "vertical-time-left",
          [`${classPrefix}-timeline--alternately`]:
            mode === "vertical-alternate",
          [`${classPrefix}-timeline--horizontal`]: mode === "horizontal",
        })}
        {...props}
      >
        {React.Children.map(children, (child, index) => {
          if (!isChildOfType(child, TimelineItem)) {
            return null;
          }
          return (
            <TimelineContext.Provider
              value={{
                light: mode === "light",
                alternately: mode === "vertical-alternate",
                index,
              }}
            >
              {child}
            </TimelineContext.Provider>
          );
        })}
        {end && <div className={`${classPrefix}-timeline-operate`}>{end}</div>}
      </div>
    );
  },
  {
    Item: TimelineItem,
  }
);

Timeline.displayName = "Timeline";
