import { type FC } from 'react';
import { Controller, useFormContext } from 'react-hook-form';

import { type FormPaginationProps } from './types';
import Pagination from '.';

export const FormPagination: FC<FormPaginationProps> = ({
  name,
  inputProps: {
    onChangePage = () => null,
    onChangeLimit = () => null,
    ...inputProps
  } = {},
  rules,
}) => {
  const { setValue, watch } = useFormContext();

  const handleChangePage = (newPage: number) => {
    setValue(`${name}.page`, newPage);
    onChangePage(newPage);
  };

  const handleChangeLimit = (newLimit: number) => {
    setValue(`${name}.limit`, newLimit);
    onChangeLimit(newLimit);
  };

  const { page, limit } = watch(name);

  return (
    <Controller
      render={({ field: { value, ref, ...field } }) => (
        <Pagination
          {...field}
          {...inputProps}
          page={page}
          limit={limit}
          onChangePage={handleChangePage}
          onChangeLimit={handleChangeLimit}
        />
      )}
      name={name}
      rules={rules}
    />
  );
};

export type { FormPaginationProps };

export default FormPagination;
