"use client"

import {ChangeEvent} from "react"
import {ImageView} from "../../atoms"
import {TextFieldProps} from "../../props"
import styles from "./styles.module.sass"

export const TextField = (props: TextFieldProps) => {
  const {
    onChangeData,
    label = "",
    error,
    tailingIcon,
    disabled = false,
    helperText,
    leadingIcon,
    wrapperClass = "",
    onClickIcon,
    maxLength,
    isRequired = true,
    placeholder,
    value = "",
    id = label ? `${label}-${Math.random()}` : `text_field-${Math.random()}`,
  } = props

  const onChangeValue = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trimStart()
    const key = e.target.name
    const data = {[key]: value}
    data[key] = value

    if (onChangeData && (!maxLength || value.length <= maxLength)) onChangeData(key ? data : value)
  }

  return (
    <div className={styles.textfield_container}>
      <div
        className={`${styles.form_input} flex ${wrapperClass}`}
        data-error={!!error}
        data-disabled={!!disabled}
        data-leading-icon={!!leadingIcon}>
        {leadingIcon && (
          <ImageView
            src={leadingIcon}
            alt="input-leading-icon"
            imgSize={24}
            wrapperClass={`${styles.leading_image_wrapper} ${styles.disabled_image}`}
            onClick={onClickIcon}
          />
        )}
        <input
          id={id}
          disabled={disabled}
          onChange={onChangeValue}
          {...props}
          placeholder={placeholder ? placeholder : "text field"}
          maxLength={maxLength}
        />
        <label htmlFor={id}>
          {label}
          {isRequired && " *"}
        </label>
        {tailingIcon && (
          <ImageView
            src={tailingIcon}
            alt="input-tailing-icon"
            imgSize={24}
            wrapperClass={`${styles.tailing_image_wrapper} ${styles.disabled_image}`}
            onClick={onClickIcon}
          />
        )}
      </div>
      <div className="flex-sb-center ">
        {helperText && <p className={styles.offer_description}>{helperText}</p>}
        {maxLength && (
          <h5 className={styles.character_count}>
            {(value as string)?.length}/{maxLength} characters
          </h5>
        )}
      </div>
      {error && <p className="error-text">{error}</p>}
    </div>
  )
}
