"use client";

var __rest = this && this.__rest || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};
import React, { useContext, useMemo, useRef } from 'react';
import classNames from 'classnames';
import useMergedState from "rc-util/es/hooks/useMergedState";
import ContextIsolator from '../_util/ContextIsolator';
import genPurePanel from '../_util/PurePanel';
import { getStatusClassNames } from '../_util/statusUtils';
import { devUseWarning } from '../_util/warning';
import { ConfigContext } from '../config-provider/context';
import DisabledContext from '../config-provider/DisabledContext';
import useCSSVarCls from '../config-provider/hooks/useCSSVarCls';
import useSize from '../config-provider/hooks/useSize';
import { FormItemInputContext } from '../form/context';
import Popover from '../popover';
import ColorPickerPanel from './ColorPickerPanel';
import ColorTrigger from './components/ColorTrigger';
import useColorState from './hooks/useColorState';
import useStyle from './style';
import { genAlphaColor, generateColor, getAlphaColor } from './util';
const ColorPicker = props => {
  const {
      value,
      defaultValue,
      format,
      defaultFormat,
      allowClear = false,
      presets,
      children,
      trigger = 'click',
      open,
      disabled,
      placement = 'bottomLeft',
      arrow = true,
      panelRender,
      showText,
      style,
      className,
      size: customizeSize,
      rootClassName,
      prefixCls: customizePrefixCls,
      styles,
      disabledAlpha = false,
      onFormatChange,
      onChange,
      onClear,
      onOpenChange,
      onChangeComplete,
      getPopupContainer,
      autoAdjustOverflow = true,
      destroyTooltipOnHide
    } = props,
    rest = __rest(props, ["value", "defaultValue", "format", "defaultFormat", "allowClear", "presets", "children", "trigger", "open", "disabled", "placement", "arrow", "panelRender", "showText", "style", "className", "size", "rootClassName", "prefixCls", "styles", "disabledAlpha", "onFormatChange", "onChange", "onClear", "onOpenChange", "onChangeComplete", "getPopupContainer", "autoAdjustOverflow", "destroyTooltipOnHide"]);
  const {
    getPrefixCls,
    direction,
    colorPicker
  } = useContext(ConfigContext);
  const contextDisabled = useContext(DisabledContext);
  const mergedDisabled = disabled !== null && disabled !== void 0 ? disabled : contextDisabled;
  const [colorValue, setColorValue, prevValue] = useColorState('', {
    value,
    defaultValue
  });
  const [popupOpen, setPopupOpen] = useMergedState(false, {
    value: open,
    postState: openData => !mergedDisabled && openData,
    onChange: onOpenChange
  });
  const [formatValue, setFormatValue] = useMergedState(format, {
    value: format,
    defaultValue: defaultFormat,
    onChange: onFormatChange
  });
  const prefixCls = getPrefixCls('color-picker', customizePrefixCls);
  const isAlphaColor = useMemo(() => getAlphaColor(colorValue) < 100, [colorValue]);
  // ===================== Form Status =====================
  const {
    status: contextStatus
  } = React.useContext(FormItemInputContext);
  // ===================== Style =====================
  const mergedSize = useSize(customizeSize);
  const rootCls = useCSSVarCls(prefixCls);
  const [wrapCSSVar, hashId, cssVarCls] = useStyle(prefixCls, rootCls);
  const rtlCls = {
    [`${prefixCls}-rtl`]: direction
  };
  const mergedRootCls = classNames(rootClassName, cssVarCls, rootCls, rtlCls);
  const mergedCls = classNames(getStatusClassNames(prefixCls, contextStatus), {
    [`${prefixCls}-sm`]: mergedSize === 'small',
    [`${prefixCls}-lg`]: mergedSize === 'large'
  }, colorPicker === null || colorPicker === void 0 ? void 0 : colorPicker.className, mergedRootCls, className, hashId);
  const mergedPopupCls = classNames(prefixCls, mergedRootCls);
  const popupAllowCloseRef = useRef(true);
  // ===================== Warning ======================
  if (process.env.NODE_ENV !== 'production') {
    const warning = devUseWarning('ColorPicker');
    process.env.NODE_ENV !== "production" ? warning(!(disabledAlpha && isAlphaColor), 'usage', '`disabledAlpha` will make the alpha to be 100% when use alpha color.') : void 0;
  }
  const handleChange = (data, type, pickColor) => {
    var _a;
    let color = generateColor(data);
    // If color is cleared, reset alpha to 100
    const isNull = value === null || !value && defaultValue === null;
    if (((_a = prevValue.current) === null || _a === void 0 ? void 0 : _a.cleared) || isNull) {
      // ignore alpha slider
      if (getAlphaColor(colorValue) === 0 && type !== 'alpha') {
        color = genAlphaColor(color);
      }
    }
    // ignore alpha color
    if (disabledAlpha && isAlphaColor) {
      color = genAlphaColor(color);
    }
    // Only for drag-and-drop color picking
    if (pickColor) {
      popupAllowCloseRef.current = false;
    } else {
      onChangeComplete === null || onChangeComplete === void 0 ? void 0 : onChangeComplete(color);
    }
    setColorValue(color);
    onChange === null || onChange === void 0 ? void 0 : onChange(color, color.toHexString());
  };
  const handleClear = () => {
    onClear === null || onClear === void 0 ? void 0 : onClear();
  };
  const handleChangeComplete = color => {
    popupAllowCloseRef.current = true;
    let changeColor = generateColor(color);
    // ignore alpha color
    if (disabledAlpha && isAlphaColor) {
      changeColor = genAlphaColor(color);
    }
    onChangeComplete === null || onChangeComplete === void 0 ? void 0 : onChangeComplete(changeColor);
  };
  const popoverProps = {
    open: popupOpen,
    trigger,
    placement,
    arrow,
    rootClassName,
    getPopupContainer,
    autoAdjustOverflow,
    destroyTooltipOnHide
  };
  const colorBaseProps = {
    prefixCls,
    color: colorValue,
    allowClear,
    disabled: mergedDisabled,
    disabledAlpha,
    presets,
    panelRender,
    format: formatValue,
    onFormatChange: setFormatValue,
    onChangeComplete: handleChangeComplete
  };
  const mergedStyle = Object.assign(Object.assign({}, colorPicker === null || colorPicker === void 0 ? void 0 : colorPicker.style), style);
  // ============================ zIndex ============================
  return wrapCSSVar( /*#__PURE__*/React.createElement(Popover, Object.assign({
    style: styles === null || styles === void 0 ? void 0 : styles.popup,
    overlayInnerStyle: styles === null || styles === void 0 ? void 0 : styles.popupOverlayInner,
    onOpenChange: visible => {
      if (popupAllowCloseRef.current && !mergedDisabled) {
        setPopupOpen(visible);
      }
    },
    content: /*#__PURE__*/React.createElement(ContextIsolator, {
      form: true
    }, /*#__PURE__*/React.createElement(ColorPickerPanel, Object.assign({}, colorBaseProps, {
      onChange: handleChange,
      onChangeComplete: handleChangeComplete,
      onClear: handleClear
    }))),
    overlayClassName: mergedPopupCls
  }, popoverProps), children || ( /*#__PURE__*/React.createElement(ColorTrigger, Object.assign({
    open: popupOpen,
    className: mergedCls,
    style: mergedStyle,
    prefixCls: prefixCls,
    disabled: mergedDisabled,
    showText: showText,
    format: formatValue
  }, rest, {
    color: colorValue
  })))));
};
if (process.env.NODE_ENV !== 'production') {
  ColorPicker.displayName = 'ColorPicker';
}
const PurePanel = genPurePanel(ColorPicker, 'color-picker', /* istanbul ignore next */
prefixCls => prefixCls, props => Object.assign(Object.assign({}, props), {
  placement: 'bottom',
  autoAdjustOverflow: false
}));
ColorPicker._InternalPanelDoNotUseOrYouWillBeFired = PurePanel;
export default ColorPicker;