"use client";

import cx from "classnames";
import React from "react";

import { useStatic } from "../../../utils/hooks";
import { Select } from "../Select";
import AutocompleteStatic from "./Autocomplete.static";

const CLASS_ROOT = "autocomplete";

export type AutocompleteOption = string | { title: string; value: string };

export interface AutocompleteProps
  extends Omit<
    React.SelectHTMLAttributes<HTMLSelectElement>,
    "size" | "value"
  > {
  /** Module config. For more see accessible-autocomplete docs */
  autocompleteConfig?: Record<string, any>;
  /** Array of string options */
  options?: AutocompleteOption[];
  /** Placeholder text */
  placeholder?: string;
  /** Additional CSS classes */
  className?: string;
  /** Select value */
  value?: string | string[];
}

const Autocomplete: React.FC<AutocompleteProps> = ({
  className,
  options = [],
  autocompleteConfig,
  placeholder,
  ...other
}) => {
  const [autocompleteRef] = useStatic(
    AutocompleteStatic as any,
    autocompleteConfig,
  );

  return (
    <Select
      className={cx(CLASS_ROOT, className)}
      data-placeholder={placeholder}
      {...(options.length ? { "data-autocomplete": true } : {})}
      {...other}
      elemRef={autocompleteRef}
    >
      {options &&
        options.map((option) => (
          <option
            label={
              typeof option === "string" && option.length === 0
                ? " "
                : undefined
            }
            value={typeof option === "string" ? option : option.value}
            key={typeof option === "string" ? option : option.value}
          >
            {typeof option === "string" ? option : option.title}
          </option>
        ))}
    </Select>
  );
};

Autocomplete.displayName = "Autocomplete";

export { Autocomplete };
