import { css } from "@emotion/react";
import type { ReactNode, Ref } from "react";
import { useState } from "react";
import type { TextFieldProps as AriaTextFieldProps } from "react-aria-components";
import { TextField as AriaTextField } from "react-aria-components";

import { SizeProvider } from "@phoenix/components/core/contexts/SizeContext";
import { fieldBaseCSS } from "@phoenix/components/core/field/styles";
import type { SizingProps } from "@phoenix/components/core/types";

import { CredentialContext } from "./CredentialContext";
import { textFieldCSS } from "./styles";

export interface CredentialFieldProps
  extends Omit<AriaTextFieldProps, "type">, SizingProps {
  children: ReactNode;
}

function CredentialField({
  ref,
  ...props
}: CredentialFieldProps & { ref?: Ref<HTMLDivElement> }) {
  const { size = "M", children, ...otherProps } = props;
  const [isVisible, setIsVisible] = useState(false);

  return (
    <CredentialContext.Provider value={{ isVisible, setIsVisible }}>
      <SizeProvider size={size}>
        <AriaTextField
          data-size={size}
          className="credential-field"
          autoComplete="off"
          ref={ref}
          {...otherProps}
          css={css(fieldBaseCSS, textFieldCSS)}
        >
          {children}
        </AriaTextField>
      </SizeProvider>
    </CredentialContext.Provider>
  );
}

export { CredentialField };
