import { View } from '@tarojs/components';
import { useSetStatus, useStatusState } from './contexts/status';
import { useMemoFn } from 'mixlea-hooks-react';
import { useSetLoaderData } from './contexts/loader-data';

import type { MlModalProps } from './types';

export function Trigger({
  triggerStyle,
  triggerClassName = 'h-full w-full flex items-center',
  disable,
  loader,
  triggerSlot,
}: Pick<MlModalProps, 'triggerStyle' | 'triggerClassName' | 'disable' | 'loader' | 'triggerSlot'>) {
  const status = useStatusState();
  const setStatus = useSetStatus();

  const setLoaderData = useSetLoaderData();

  const handleTrigger = useMemoFn(() => {
    if (disable) {
      return;
    }

    if (loader) {
      setStatus('loading');

      loader()
        .then((data) => setLoaderData(data))
        .then(() => setStatus('activating'))
        .catch(() => {
          setStatus('inactive');
        });
    } else {
      setStatus('activating');
    }
  });

  return (
    <View style={triggerStyle} className={triggerClassName} onClick={handleTrigger}>
      {triggerSlot({ status })}
    </View>
  );
}
