import React, { useContext } from "react";
import classNames from "classnames";
import { RegionFlag } from "./RegionFlag";
import { useConfig } from "../_util/config-context";
import { noop } from "../_util/noop";
import { StyledProps } from "../_type";

export interface RegionOptionProps extends StyledProps {
  /**
   * 地域值
   */
  value: string;

  /**
   * 地域显示文案
   */
  children?: React.ReactNode;

  /**
   * 是否被选中
   *
   * **如在 `RegionSelect` 中使用，无需传值**
   */
  selected?: boolean;

  /**
   * 是否显示提醒小红点
   * @default false
   */
  dot?: boolean;

  /**
   * 被点击时回调
   */
  onClick?: React.MouseEventHandler;

  /**
   * 数值信息
   * @since 2.5.0
   */
  num?: React.ReactNode;

  /**
   * 是否禁用
   * @since 2.5.0
   */
  disabled?: boolean;

  /**
   * 已废弃
   * @deprecated
   */
  flag?: string;

  /**
   * 已废弃
   * @deprecated
   */
  country?: string;
}

export interface RegionOptionContext {
  inject?: (props: RegionOptionProps) => RegionOptionProps;
  shortcut?: {
    title?: React.ReactNode;
    options?: RegionOptionProps[];
  };
}
export const RegionOptionContext = React.createContext<RegionOptionContext>({});

export const RegionOption = React.forwardRef(function RegionOption(
  props: RegionOptionProps,
  ref: React.Ref<HTMLDivElement>
) {
  const { classPrefix } = useConfig();
  const { inject } = useContext(RegionOptionContext);

  if (inject) {
    props = inject(props); // eslint-disable-line no-param-reassign
  }

  const {
    children,
    dot,
    num,
    selected,
    disabled,
    onClick,
    value,
    flag,
    country,
    className,
    ...restProps
  } = props;

  return (
    <div
      ref={ref}
      className={classNames(`${classPrefix}-region__item`, className, {
        "is-selected": selected,
        "is-disabled": disabled,
      })}
      onClick={disabled ? noop : onClick}
      {...restProps}
    >
      <RegionFlag />
      <span className={`${classPrefix}-region__name`}>
        {children}
        {!!num && <span className={`${classPrefix}-region__num`}>{num}</span>}
        {dot && <i className={`${classPrefix}-region__new`} />}
      </span>
    </div>
  );
});

RegionOption.displayName = "RegionOption";
