"use client";
import { autocompleteVariants } from '@heroui/styles';
import { mergeRefs } from '@react-aria/utils';
import React__default, { useRef, createContext, useContext } from 'react';
import { Select, SelectStateContext, Autocomplete, Popover, Button, SelectValue, Group } from 'react-aria-components';
import { dataAttr } from '../../utils/assertion.js';
import { composeTwRenderProps, composeSlotClassName } from '../../utils/compose.js';
import { CloseIcon, IconChevronDown } from '../icons.js';
import { jsx, Fragment } from 'react/jsx-runtime';
import { SurfaceContext } from '../surface/surface.js';

const AutocompleteContext = /*#__PURE__*/createContext({
  triggerRef: {
    current: null
  },
  clearButtonRef: {
    current: null
  }
});

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Root
 * -----------------------------------------------------------------------------------------------*/

const AutocompleteRoot = ({
  children,
  className,
  fullWidth,
  onClear,
  variant,
  ...props
}) => {
  const slots = React__default.useMemo(() => autocompleteVariants({
    fullWidth,
    variant
  }), [fullWidth, variant]);
  const triggerRef = useRef(null);
  const clearButtonRef = useRef(null);
  return /*#__PURE__*/jsx(AutocompleteContext, {
    value: {
      slots,
      triggerRef,
      clearButtonRef,
      onClear
    },
    children: /*#__PURE__*/jsx(Select, {
      "data-slot": "autocomplete",
      ...props,
      className: composeTwRenderProps(className, slots?.base()),
      children: values => /*#__PURE__*/jsx(Fragment, {
        children: typeof children === "function" ? children(values) : children
      })
    })
  });
};

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Trigger
 * -----------------------------------------------------------------------------------------------*/

const AutocompleteTrigger = /*#__PURE__*/React__default.forwardRef(({
  children,
  className,
  onClick,
  ...props
}, ref) => {
  const {
    clearButtonRef,
    slots,
    triggerRef
  } = useContext(AutocompleteContext);
  const state = useContext(SelectStateContext);

  // Callback ref to update context ref
  const contextRefCallback = React__default.useCallback(node => {
    triggerRef.current = node;
  }, [triggerRef]);

  // Merge context ref callback with user-provided ref
  const mergedRef = mergeRefs(contextRefCallback, ref);
  const handleClick = e => {
    // Don't toggle if clicking the clear button
    if (clearButtonRef.current?.contains(e.target)) {
      return;
    }
    onClick?.(e);
    state?.toggle();
  };
  return /*#__PURE__*/jsx(Group, {
    ref: mergedRef,
    className: composeTwRenderProps(className, slots?.trigger()),
    "data-slot": "autocomplete-trigger",
    onClick: handleClick,
    ...props,
    children: values => /*#__PURE__*/jsx(Fragment, {
      children: typeof children === "function" ? children(values) : children
    })
  });
});
AutocompleteTrigger.displayName = "AutocompleteTrigger";

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Value
 * -----------------------------------------------------------------------------------------------*/

const AutocompleteValue = ({
  children,
  className,
  ...props
}) => {
  const {
    slots
  } = useContext(AutocompleteContext);
  return /*#__PURE__*/jsx(SelectValue, {
    className: composeTwRenderProps(className, slots?.value()),
    "data-slot": "autocomplete-value",
    ...props,
    children: children
  });
};

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Indicator
 * -----------------------------------------------------------------------------------------------*/

const AutocompleteIndicator = ({
  children,
  className,
  ...props
}) => {
  const {
    slots
  } = useContext(AutocompleteContext);
  const state = useContext(SelectStateContext);
  if (children && /*#__PURE__*/React__default.isValidElement(children)) {
    return /*#__PURE__*/React__default.cloneElement(children, {
      ...props,
      className: composeSlotClassName(slots?.indicator, className),
      "data-slot": "autocomplete-indicator",
      "data-open": dataAttr(state?.isOpen)
    });
  }
  return /*#__PURE__*/jsx(Button, {
    children: /*#__PURE__*/jsx(IconChevronDown, {
      className: composeSlotClassName(slots?.indicator, className),
      "data-open": dataAttr(state?.isOpen),
      "data-slot": "autocomplete-default-indicator",
      ...props
    })
  });
};

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Popover
 * -----------------------------------------------------------------------------------------------*/

const AutocompletePopover = ({
  children,
  className,
  placement = "bottom",
  ...props
}) => {
  const {
    slots,
    triggerRef
  } = useContext(AutocompleteContext);
  return /*#__PURE__*/jsx(SurfaceContext, {
    value: {
      variant: "default"
    },
    children: /*#__PURE__*/jsx(Popover, {
      ...props,
      className: composeTwRenderProps(className, slots?.popover()),
      "data-slot": "autocomplete-popover",
      placement: placement,
      triggerRef: triggerRef,
      children: children
    })
  });
};

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Filter
 * -----------------------------------------------------------------------------------------------*/

const AutocompleteFilter = ({
  children,
  ...props
}) => {
  return /*#__PURE__*/jsx(Autocomplete, {
    "data-slot": "autocomplete-filter",
    ...props,
    children: children
  });
};

/* -------------------------------------------------------------------------------------------------
 * Autocomplete Clear Button
 * -----------------------------------------------------------------------------------------------*/

const AutocompleteClearButton = ({
  className,
  onClick,
  ref,
  ...props
}) => {
  const {
    slots
  } = useContext(AutocompleteContext);
  const state = useContext(SelectStateContext);
  const {
    clearButtonRef,
    onClear
  } = useContext(AutocompleteContext);
  const clearButtonRefCallback = React__default.useCallback(node => {
    clearButtonRef.current = node;
  }, [clearButtonRef]);

  // Merge context ref callback with user-provided ref
  const mergedRef = mergeRefs(clearButtonRefCallback, ref);
  const handleClick = e => {
    state?.selectionManager.setSelectedKeys(new Set());
    onClear?.();
    onClick?.(e);
  };
  return /*#__PURE__*/jsx("button", {
    ref: mergedRef,
    className: slots?.clearButton({
      className
    }),
    "data-empty": dataAttr(state?.selectionManager.selectedKeys.size === 0),
    "data-slot": "autocomplete-clear-button",
    onClick: handleClick,
    ...props,
    children: /*#__PURE__*/jsx(CloseIcon, {
      "data-slot": "autocomplete-clear-button-icon"
    })
  });
};

export { AutocompleteClearButton, AutocompleteFilter, AutocompleteIndicator, AutocompletePopover, AutocompleteRoot, AutocompleteTrigger, AutocompleteValue };
