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

export function Panel({
  placement,
  panelStyle,
  panelClassName,

  children,
}: PropsWithChildren<Pick<MlModalProps, 'placement' | 'panelStyle' | 'panelClassName'>>) {
  const status = useStatusState();
  const setStatus = useSetStatus();

  const handleAnimationEnd = useMemoFn((e: any) => {
    e.stopPropagation();
    e.preventDefault();

    if (e.currentTarget.animationName.includes('slide-from')) {
      setStatus('active');
    } else if (e.currentTarget.animationName.includes('slide-to')) {
      setStatus('inactive');
    }
  });

  return (
    <View
      style={panelStyle}
      className={classNames(
        panelClassName,
        'bg-[--block-bg-color]',

        {
          'animated__slide-from-top': status === 'activating' && placement === 'top',
          'animated__slide-from-right': status === 'activating' && placement === 'right',
          'animated__slide-from-bottom': status === 'activating' && placement === 'bottom',
          'animated__slide-from-opacity0': status === 'activating' && placement === 'center',
          'animated__slide-from-left': status === 'activating' && placement === 'left',

          'animated__slide-to-top': status === 'inactivating' && placement === 'top',
          'animated__slide-to-right': status === 'inactivating' && placement === 'right',
          'animated__slide-to-bottom': status === 'inactivating' && placement === 'bottom',
          'animated__slide-to-left': status === 'inactivating' && placement === 'left',
          'animated__slide-to-opacity0': status === 'inactivating' && placement === 'center',
        },
      )}
      onAnimationEnd={handleAnimationEnd}
      onClick={stopEvent}
    >
      {children}
    </View>
  );
}
