import type { FieldValues } from 'react-hook-form';

import { useState } from 'react';

import type { FormerProps } from './Former.types';

export type UseFormerStateProps<T extends FieldValues = FieldValues> = Pick<
  FormerProps<T>,
  'onChange' | 'onClose' | 'opened' | 'primeData' | 'request' | 'values'
>;

export const useFormerState = <T extends FieldValues = FieldValues>(
  options?: Partial<UseFormerStateProps<T>>
) => {
  const [state, setState] = useState<UseFormerStateProps<T>>({
    onChange: options?.onChange,
    onClose: options?.onClose ?? (() => setState((cv) => ({ ...cv, opened: false }))),
    opened: options?.opened ?? false,
    primeData: options?.primeData ?? options?.values,
    request: options?.request ?? 'insert',
    values: options?.values,
  });

  const updateState = (updates: Partial<UseFormerStateProps<T>>) => {
    setState((prev) => ({ ...prev, ...updates }));
  };

  const { onChange, onClose, opened, ...formerProps } = state;

  return {
    former: { ...formerProps, onChange },
    formerWrapper: { onClose, opened } as {
      onClose: Required<UseFormerStateProps<T>>['onClose'];
      opened: Required<UseFormerStateProps<T>>['opened'];
    },
    open: (request: UseFormerStateProps<T>['request'], data: UseFormerStateProps<T>['values']) => {
      setState((cv) => ({ ...cv, opened: true, primeData: data, request, values: data }));
    },
    updateState,
  };
};
