import { getMergedObj } from "@web3r/flowerkit/obj";
import type {
  FC, PropsWithChildren, ReactElement,
} from "react";
import { useMemo, useContext } from "react";
import { ModalContent } from "./ModalContent";
import { ModalFooter } from "./ModalFooter";
import { ModalHeader } from "./ModalHeader";
import { ModalTitle } from "./ModalTitle";
import type { TModalContext, TPresetData } from "../config/types";
import { ModalContext } from "../context";
import { getPresetPartials } from "../lib";

/**
 * Содержимое для модального окна
 * @returns {ReactElement}
 */
export const ModalInner: FC<PropsWithChildren> = ({ children }): ReactElement => {

  const {
    id, preset, headerSlot, titleSlot, footerSlot, getCN,
  } = useContext<TModalContext>(ModalContext);

  const partials = useMemo<TPresetData>(() => {
    const userPartials = {
      titleSlot,
      contentSlot: children,
      footerSlot,
    };
    if (preset) {
      const presetPartials = getPresetPartials(preset, id, getCN);
      return getMergedObj<TPresetData>(userPartials, presetPartials);
    } else {
      return userPartials;
    }
  }, [ preset, titleSlot, footerSlot, children ]);

  return (
    <>
      {headerSlot || !!partials.titleSlot && (
        <ModalHeader>
          <ModalTitle>{partials.titleSlot}</ModalTitle>
        </ModalHeader>
      )}
      {!!partials.contentSlot && <ModalContent>{partials.contentSlot}</ModalContent>}
      {!!partials.footerSlot && <ModalFooter>{partials.footerSlot}</ModalFooter>}
    </>
  );

};

