import type { FetcherWithComponents, FormProps } from "@remix-run/react";
import type { ReactElement, ReactNode } from "react";

import { Form } from "@remix-run/react";
import { useHydrated } from "remix-utils";

export let NoJS = ({ children }: { children: ReactElement }) => {
  let isHydrated = useHydrated();

  if (!isHydrated) {
    return children;
  } else {
    return null;
  }
};

export let HasJS = ({ children }: { children: ReactElement }) => {
  let isHydrated = useHydrated();

  if (isHydrated) {
    return children;
  } else {
    return null;
  }
};

export let ProgessiveEnhancement = ({
  children,
  fallback,
}: {
  children: ReactElement;
  fallback: ReactElement;
}) => {
  let isHydrated = useHydrated();

  if (isHydrated) {
    return children;
  } else {
    return fallback;
  }
};

export let ProgressiveForm = ({
  fetcher,
  children,
  ...props
}: {
  children: ReactNode;
  fetcher?: FetcherWithComponents<any>;
} & FormProps) => {
  let isHydrated = useHydrated();

  let NoJS = () => (
    <input type="hidden" name="no-js" value={String(!isHydrated)} />
  );

  if (fetcher) {
    return (
      <fetcher.Form {...props}>
        <NoJS />
        {children}
      </fetcher.Form>
    );
  } else {
    return (
      <Form {...props}>
        <NoJS />
        {children}
      </Form>
    );
  }
};
