"use client";

import { type InputHTMLAttributes, useId } from "react";
import clsx from "clsx";

import Typography from "../Typography/Typography";

import styles from "./TextInput.module.scss";

export interface TextInputProps extends InputHTMLAttributes<HTMLInputElement> {
  error?: string;
  containerClassName?: string;
  placeholderDisplayMode?: "label" | "placeholder";
}

export default function TextInput({
  placeholder,
  type = "text",
  error,
  className,
  containerClassName,
  placeholderDisplayMode = "label",
  children,
  ...props
}: TextInputProps) {
  const id = useId();

  return (
    <div className={clsx(styles.container, containerClassName)}>
      <input
        id={id}
        type={type}
        className={clsx(styles.input, error && styles.inputError, className)}
        {...props}
        placeholder={placeholderDisplayMode === "label" ? "" : placeholder}
      />
      {placeholderDisplayMode === "label" && (
        <label htmlFor={id} className={styles.label}>
          <Typography color="secondary">{placeholder}</Typography>
        </label>
      )}
      {children}
      {error && (
        <Typography
          as="p"
          size="xs"
          color="danger"
          className={styles.errorText}
        >
          {error}
        </Typography>
      )}
    </div>
  );
}
