'use client';

import { useState, useCallback } from 'react';

export interface FieldErrors {
  [field: string]: string;
}

export interface UseFormErrorsReturn {
  /** Current field errors */
  errors: FieldErrors;
  /** Set error for a specific field */
  setFieldError: (field: string, message: string) => void;
  /** Clear error for a specific field */
  clearFieldError: (field: string) => void;
  /** Set multiple field errors at once */
  setErrors: (errors: FieldErrors) => void;
  /** Clear all errors */
  clearErrors: () => void;
  /** Check if a field has an error */
  hasError: (field: string) => boolean;
  /** Get error message for a field */
  getError: (field: string) => string | undefined;
  /** Check if any errors exist */
  hasAnyErrors: boolean;
}

/**
 * Hook for managing form field errors.
 * Works well with ApiClientError.getFieldErrors().
 *
 * @example
 * const { errors, setErrors, clearErrors, hasError, getError } = useFormErrors();
 *
 * const handleSubmit = async (data) => {
 *   clearErrors();
 *   try {
 *     await api.post('/users', data);
 *   } catch (error) {
 *     if (isApiClientError(error) && error.isValidationError()) {
 *       setErrors(error.getFieldErrors());
 *     }
 *   }
 * };
 *
 * return (
 *   <FormField
 *     name="email"
 *     label="Email"
 *     error={getError('email')}
 *   />
 * );
 */
export function useFormErrors(initialErrors: FieldErrors = {}): UseFormErrorsReturn {
  const [errors, setErrorsState] = useState<FieldErrors>(initialErrors);

  const setFieldError = useCallback((field: string, message: string) => {
    setErrorsState((prev) => ({ ...prev, [field]: message }));
  }, []);

  const clearFieldError = useCallback((field: string) => {
    setErrorsState((prev) => {
      const next = { ...prev };
      delete next[field];
      return next;
    });
  }, []);

  const setErrors = useCallback((newErrors: FieldErrors) => {
    setErrorsState(newErrors);
  }, []);

  const clearErrors = useCallback(() => {
    setErrorsState({});
  }, []);

  const hasError = useCallback(
    (field: string) => {
      return !!errors[field];
    },
    [errors]
  );

  const getError = useCallback(
    (field: string) => {
      return errors[field];
    },
    [errors]
  );

  const hasAnyErrors = Object.keys(errors).length > 0;

  return {
    errors,
    setFieldError,
    clearFieldError,
    setErrors,
    clearErrors,
    hasError,
    getError,
    hasAnyErrors,
  };
}
