import React, { useMemo } from "react";
import { isNumber } from "@reins/utils";

import { FormAdapter } from "utils";

export type FormPageProps = {
  page: number | "firstPage" | "notFirstPage" | "lastPage" | "notLastPage" | "extremePages" | "restPages" | "all";
  children: React.ReactNode;
};

export const FormPage: React.FC<
  FormPageProps & {
    useFormContext: (componentName: string) => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      form: FormAdapter<any, any>;
    };
  }
> = ({ page, children, useFormContext }) => {
  const { form } = useFormContext("FormPage");

  const [{ page: formPage, isFirstPage, isLastPage, isMultiPage }] = form.store.useStore({
    selector: (state) => ({
      page: state.page,
      isMultiPage: state.pages > 1,
      isFirstPage: state.page === 1,
      isLastPage: state.page === state.pages,
    }),
  });

  const canShowPage = useMemo(() => {
    if (isNumber(page)) return page === formPage;

    switch (page) {
      case "firstPage": {
        return isFirstPage;
      }
      case "notFirstPage": {
        return !isFirstPage;
      }
      case "lastPage": {
        return isLastPage;
      }
      case "notLastPage": {
        return !isLastPage;
      }
      case "extremePages": {
        return isFirstPage || isLastPage;
      }
      case "restPages": {
        return !isFirstPage && !isLastPage;
      }
      case "all": {
        return true;
      }
      default: {
        return false;
      }
    }
  }, [page, formPage, isFirstPage, isLastPage]);

  if (!isMultiPage) {
    console.warn(
      "You are using 'FormPage' within 'Form' which is 'single-paged'. " +
        "This is most-likely not what supposed to be. " +
        "Please use 'FormPage' component in 'multi-step' form via passing 'pages' prop to 'Form' component. " +
        "Otherwise it will render it everytime.",
    );
    return children;
  }

  if (!canShowPage) return null;

  return children;
};
