"use client"

import {useCommon} from "@fanam-pkg/core-utils"
import {ChangeEvent, FormEvent} from "react"
import {ImageView} from "../../atoms"
import {TextFieldProps} from "../../props"
import styles from "./styles.module.sass"

export const TextField = (props: TextFieldProps) => {
  const {isValidInputByRegex} = useCommon()

  const {
    onChangeData,
    label = "",
    error,
    tailingIcon,
    disabled = false,
    helperText,
    leadingIcon,
    wrapperClass = "",
    onClickIcon,
    maxLength,
    placeholder,
    inputRegex,
    isRequired = true,
    autoComplete = "off",
    id = label ? `${label}-${Math.random()}` : `text_field-${Math.random()}`,
    value,
  } = 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)
  }

  const onInputChange = (e: FormEvent<HTMLInputElement>) => {
    if (inputRegex) {
      const {value} = e.currentTarget
      if (!isValidInputByRegex(value, inputRegex)) {
        e.currentTarget.value = value.slice(0, -1)
      }
    }
  }

  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}
          onInput={onInputChange}
          {...props}
          placeholder={placeholder ? placeholder : "text field"}
          maxLength={maxLength}
          autoComplete={autoComplete}
        />
        <label htmlFor={id}>
          {label}
          {isRequired && <small className="required_icon">*</small>}
        </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}`.length}/{maxLength} characters
          </h5>
        )}
      </div>
      {error && <p className="error-text">{error}</p>}
    </div>
  )
}
