import { useState, useCallback } from "react";
import type { ZodSchema, ZodError } from "zod";

interface UseFormValidationOptions<T> {
  schema: ZodSchema<T>;
}

export function useFormValidation<T>({ schema }: UseFormValidationOptions<T>) {
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validate = useCallback(
    (data: unknown): data is T => {
      try {
        schema.parse(data);
        setErrors({});
        return true;
      } catch (err) {
        const zodError = err as ZodError;
        const fieldErrors: Record<string, string> = {};
        for (const issue of zodError.issues) {
          const path = issue.path.join(".");
          if (!fieldErrors[path]) {
            fieldErrors[path] = issue.message;
          }
        }
        setErrors(fieldErrors);
        return false;
      }
    },
    [schema]
  );

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

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

  return { errors, validate, clearErrors, clearField };
}
