import type { StringLike } from "@ariakit/components/form/types";
import { useStoreState } from "@ariakit/react-store";
import {
  useMergeRefs,
  createElement,
  createHook,
  forwardRef,
  memo,
} from "@ariakit/react-utils";
import type { Props } from "@ariakit/react-utils";
import type { ElementType } from "react";
import type { CollectionItemOptions } from "../collection/collection-item.tsx";
import { useCollectionItem } from "../collection/collection-item.tsx";
import { useFormItem } from "./form-context.tsx";
import type { FormStore } from "./form-store.ts";

const TagName = "div" satisfies ElementType;
type TagName = typeof TagName;
type HTMLType = HTMLElementTagNameMap[TagName];

/**
 * Returns props to create a `FormError` component.
 * @see https://ariakit.com/components/form
 * @example
 * ```jsx
 * const store = useFormStore({ defaultValues: { email: "" } });
 * const props = useFormError({ store, name: store.names.email });
 *
 * useFormValidate(store, () => {
 *   if (!store.getValue(store.names.email)) {
 *     store.setError(store.names.email, "Email is required!");
 *   }
 * });
 *
 * <Form store={store}>
 *   <FormLabel name={store.names.email}>Email</FormLabel>
 *   <FormInput name={store.names.email} />
 *   <Role {...props} />
 * </Form>
 * ```
 */
export const useFormError = createHook<TagName, FormErrorOptions>(
  function useFormError({
    store,
    name: nameProp,
    getItem: getItemProp,
    ...props
  }) {
    const {
      store: form,
      name,
      id,
      ref,
      getItem,
    } = useFormItem<HTMLType>({
      store,
      name: nameProp,
      id: props.id,
      type: "error",
      getItem: getItemProp,
      component: "FormError",
    });

    const children = useStoreState(form, ["errors", "touched"], () => {
      const error = form.getError(name);
      if (error == null) return;
      if (!form.getFieldTouched(name)) return;
      return error;
    });

    props = {
      role: "alert",
      children,
      ...props,
      id,
      ref: useMergeRefs(ref, props.ref),
    };

    props = useCollectionItem({ store: form, ...props, getItem });

    return props;
  },
);

/**
 * Renders an element that shows an error message. The `children` will
 * automatically display the error message defined in the store.
 * @see https://ariakit.com/components/form
 * @example
 * ```jsx {16}
 * const form = useFormStore({
 *   defaultValues: {
 *     email: "",
 *   },
 * });
 *
 * useFormValidate(form, () => {
 *   if (!form.getValue(form.names.email)) {
 *     form.setError(form.names.email, "Email is required!");
 *   }
 * });
 *
 * <Form store={form}>
 *   <FormLabel name={form.names.email}>Email</FormLabel>
 *   <FormInput name={form.names.email} />
 *   <FormError name={form.names.email} />
 * </Form>
 * ```
 */
export const FormError = memo(
  forwardRef(function FormError(props: FormErrorProps) {
    const htmlProps = useFormError(props);
    return createElement(TagName, htmlProps);
  }),
);

export interface FormErrorOptions<
  T extends ElementType = TagName,
> extends CollectionItemOptions<T> {
  /**
   * Object returned by the
   * [`useFormStore`](https://ariakit.com/reference/use-form-store) hook. If not
   * provided, the closest [`Form`](https://ariakit.com/reference/form) or
   * [`FormProvider`](https://ariakit.com/reference/form-provider) components'
   * context will be used.
   */
  store?: FormStore;
  /**
   * Name of the field associated with this error. This can either be a string
   * or a reference to a field name from the
   * [`names`](https://ariakit.com/reference/use-form-store#names) object in the
   * store, for type safety.
   * @example
   * ```jsx
   * <FormError name="password" />
   * ```
   */
  name: StringLike;
}

export type FormErrorProps<T extends ElementType = TagName> = Props<
  T,
  FormErrorOptions<T>
>;
