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

const ResponsiveConfig = {
  xs: 375,
  // 从这里开始变为移动端试图
  sm: 768,
  md: 1024,
  lg: 1280,
  xl: 1440,
};
export const useMedia = (config: Record<string, number> = ResponsiveConfig) => {
  // 追踪客户端是否已挂载
  const [mounted, setMounted] = useState(false);
  const [response, setResponse] = useState<Record<keyof typeof config, boolean>>();

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

  // 在服务端渲染和客户端首次渲染时返回 undefined，避免 hydration 不匹配
  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,
  };
};
