'use client';
import { useMemoizedFn } from 'ahooks';
import { useEffect, useState } from 'react';

export const useMedia = (config: Record<string, number>) => {
  // 追踪客户端是否已挂载
  const [mounted, setMounted] = useState(false);
  const [response, setResponse] = useState<Record<keyof typeof config, boolean>>();

  useEffect(() => {
    setMounted(true);
    const onResize = () => {
      const newResponse = Object.fromEntries(
        Object.entries(config).map(([key, value]) => {
          if (window.innerWidth > value) {
            return [key, true];
          }
          return [key, false];
        })
      ) as Record<keyof typeof config, boolean>;
      setResponse(newResponse);
    };
    window.addEventListener('resize', onResize);
    onResize();
    return () => window.removeEventListener('resize', onResize);
  }, []);

  if (!mounted) return undefined;

  return response;
};

/**
 * 异步函数hook, 自动托管loading状态
 * @param fn 异步函数
 * @returns 异步函数执行结果
 */
export const useAsyncFn = <T extends (...args: any[]) => Promise<any>>(
  fn: T
): {
  loading: boolean;
  run: T;
} => {
  const [loading, setLoading] = useState(false);

  const run = useMemoizedFn(async (...args: Parameters<T>) => {
    setLoading(true);
    try {
      const result = await fn(...args);
      return result;
    } finally {
      setLoading(false);
    }
  }) as T;

  return {
    loading,
    run,
  };
};
