/**
 * Hook for managing threshold input state and validation
 */

import { useState, useCallback } from 'react';

export function useThreshold(initialValue: string = '7') {
  const [threshold, setThreshold] = useState(initialValue);
  const [thresholdError, setThresholdError] = useState<string | null>(null);

  const handleThresholdChange = useCallback((value: string) => {
    // Allow empty string while typing
    if (value === '') {
      setThreshold('');
      setThresholdError(null);
      return;
    }
    // Parse as integer
    const numValue = parseInt(value, 10);
    // Validate: must be a positive integer >= 1
    if (isNaN(numValue) || numValue < 1) {
      setThresholdError('Minimum threshold is 1 day');
      setThreshold(value); // Keep the invalid value for user to see
    } else {
      setThresholdError(null);
      setThreshold(value);
    }
  }, []);

  const handleThresholdBlur = useCallback(() => {
    // If empty or invalid on blur, reset to minimum (1)
    if (threshold === '' || isNaN(parseInt(threshold, 10)) || parseInt(threshold, 10) < 1) {
      setThreshold('1');
      setThresholdError(null);
    }
  }, [threshold]);

  return {
    threshold,
    thresholdError,
    setThreshold,
    handleThresholdChange,
    handleThresholdBlur,
  };
}

