import { useCallback, useState } from 'react';
import type { FormErrors } from '../types';

export function useFormValidation<T>(initialData: T, validateFn: (data: T) => FormErrors) {
  const [formData, setFormData] = useState<T>(initialData);
  const [errors, setErrors] = useState<FormErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const updateField = useCallback(
    (field: keyof T, value: T[keyof T]) => {
      setFormData(prev => ({ ...prev, [field]: value }));

      // Clear error when user starts typing
      if (errors[field as string]) {
        setErrors(prev => ({ ...prev, [field as string]: '' }));
      }
    },
    [errors]
  );

  const validate = useCallback((): boolean => {
    const newErrors = validateFn(formData);
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formData, validateFn]);

  const reset = useCallback(() => {
    setFormData(initialData);
    setErrors({});
    setIsSubmitting(false);
  }, [initialData]);

  const handleSubmit = useCallback(
    async (
      onSubmit: (data: T) => Promise<void>,
      onSuccess?: () => void,
      onError?: (error: unknown) => void
    ) => {
      if (!validate()) {
        return;
      }

      setIsSubmitting(true);
      try {
        await onSubmit(formData);
        reset();
        onSuccess?.();
      } catch (error) {
        onError?.(error);
      } finally {
        setIsSubmitting(false);
      }
    },
    [formData, validate, reset]
  );

  return {
    formData,
    errors,
    isSubmitting,
    updateField,
    validate,
    reset,
    handleSubmit,
    setIsSubmitting,
  };
}
