import { RootPortal, View } from '@tarojs/components';
import { classNames } from 'mixlea-utils-js';
import type { PropsWithChildren } from 'react';
import type { MlModalProps } from './types';
import { stopEvent } from './tools/stop-event';
import { useSetStatus, useStatusState } from './contexts/status';
import { useMemoFn } from 'mixlea-hooks-react';

export function ModalContainer({
  placement,
  maskCloseable,
  children,
}: PropsWithChildren<Pick<MlModalProps, 'placement' | 'maskCloseable'>>) {
  const status = useStatusState();
  const setStatus = useSetStatus();

  const handleClick = useMemoFn(() => {
    if (maskCloseable) {
      setStatus('inactivating');
    }
  });

  if (!['inactivating', 'activating', 'active'].includes(status)) {
    return null;
  }

  return (
    <RootPortal enable>
      <View
        className={classNames(
          'fixed top-0 left-0 h-full w-full z-[999] flex bg-black/30  border-4 border-red-500',
          {
            'items-start justify-center': placement === 'top',
            'items-center justify-end': placement === 'right',
            'items-end justify-center': placement === 'bottom',
            'items-center justify-start': placement === 'left',
            'items-center justify-center': placement === 'center',
          },
          {
            'animated__fade-in': status === 'activating',
            'animated__fade-out': status === 'inactivating',
          },
        )}
        catchMove
        onTouchMove={stopEvent}
        onClick={handleClick}
      >
        {children}
      </View>
    </RootPortal>
  );
}
