import React, { useState } from 'react'

import styles from './RangeFilter.module.scss'
import TextInput from '../Form/TextInput'
import { c } from '../../translations/LibraryTranslationService'

export type MinMaxRange = {
  min?: number
  max?: number
}

export type RangeProps = {
  /** Selected min-max values */
  selectedValues: MinMaxRange
  /** Function to update filter values */
  onChangeCallout?: (value: MinMaxRange) => void
  /** Optional label for min input */
  labelTextMin?: string
  /** Optional label for max input */
  labelTextMax?: string
  /** Optional placeholder for min input */
  placeholderMin?: string
  /** Optional placeholder for max input */
  placeholderMax?: string
}

const RangeFilter = (filterValues: RangeProps): React.JSX.Element => {
  const {
    selectedValues,
    onChangeCallout,
    labelTextMin,
    labelTextMax,
    placeholderMin,
    placeholderMax,
  } = filterValues
  const [error, setError] = useState(false)

  return (
    <div className={styles.rangeMainContainer}>
      <div className={styles.valueContainer}>
        <TextInput
          value={selectedValues?.min ?? ''}
          type='number'
          classType='rangeInput'
          labelText={labelTextMin ?? c('minimum')}
          placeholder={placeholderMin ?? c('addMin')}
          onlyPositiveNumbers
          callout={(_, value) => {
            const updatedMin = value === '' ? undefined : Number(value)
            if (
              selectedValues?.max !== undefined &&
              updatedMin !== undefined &&
              updatedMin > selectedValues.max
            ) {
              setError(true)
            } else {
              setError(false)
              const updatedRange = { ...selectedValues, min: updatedMin }
              onChangeCallout?.(updatedRange)
            }
          }}
        />
        <div className={styles.separator}>-</div>
        <TextInput
          value={selectedValues?.max ?? ''}
          type='number'
          classType='rangeInput'
          labelText={labelTextMax ?? c('maximum')}
          placeholder={placeholderMax ?? c('addMax')}
          onlyPositiveNumbers
          callout={(_, value) => {
            const updatedMax = value === '' ? undefined : Number(value)
            if (
              selectedValues?.min !== undefined &&
              updatedMax !== undefined &&
              updatedMax < selectedValues.min
            ) {
              setError(true)
            } else {
              setError(false)
              const updatedRange = { ...selectedValues, max: updatedMax }
              onChangeCallout?.(updatedRange)
            }
          }}
        />
      </div>
      {error ? (
        <div className={styles.error}>
          {c('minValueCantBeGreaterThanMaxValue')}
        </div>
      ) : null}
    </div>
  )
}

export default RangeFilter
