import { LoadingOverlay, ScrollAreaAutosize } from '@mantine/core';
import { type PropsWithChildren, useEffect } from 'react';

import { useFormerStore } from './Former.store';
import { FormerLayoutBottom } from './FormerLayoutBottom';
import { FormerLayoutTop } from './FormerLayoutTop';

export const FormerLayout = (props: PropsWithChildren) => {
  const {
    disableHTMlForm,
    getFormMethods,
    id,
    load,
    loading,
    loadingOverlayProps,
    opened,
    request,
    reset,
    save,
    scrollAreaProps,
  } = useFormerStore((state) => ({
    disableHTMlForm: state.disableHTMlForm,
    getFormMethods: state.getFormMethods,
    id: state.id,
    load: state.load,
    loading: state.loading,
    loadingOverlayProps: state.loadingOverlayProps,
    opened: state.opened,
    request: state.request,
    reset: state.reset,
    save: state.save,

    scrollAreaProps: state.scrollAreaProps,
  }));

  useEffect(() => {
    if (getFormMethods) {
      const formMethods = getFormMethods();
      if (formMethods && request !== 'insert') {
        load(true);
      }
    }
  }, [getFormMethods, request, opened]);

  return (
    <>
      <FormerLayoutTop />
      <ScrollAreaAutosize
        offsetScrollbars
        scrollbarSize={4}
        type="auto"
        {...scrollAreaProps}
        style={{
          height: '100%',
          padding: '0.25rem',
          width: '100%',
          ...scrollAreaProps?.style,
        }}
      >
        {disableHTMlForm ? (
          // eslint-disable-next-line react/no-unknown-property
          <div key={`former_d${id}`} x-data-request={request}>
            {props.children}
          </div>
        ) : (
          <form
            id={`former_f${id}`}
            key={`former_${id}`}
            onReset={(e) => reset(e)}
            onSubmit={(e) => save(e)}
            // eslint-disable-next-line react/no-unknown-property
            x-data-request={request}
          >
            {props.children}
          </form>
        )}

        <LoadingOverlay
          loaderProps={{ type: 'bars' }}
          overlayProps={{
            backgroundOpacity: 0.5,
          }}
          {...loadingOverlayProps}
          visible={loading}
        />
      </ScrollAreaAutosize>
      <FormerLayoutBottom />
    </>
  );
};
