import { useState, useCallback } from "react";
import { message } from "antd";
import { resourceService } from "@/services/supabase/resource";

export const useResources = (initialPagination, initialSorter, type) => {
  const [resources, setResources] = useState([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPagination, setCurrentPagination] = useState(initialPagination);
  const [currentSorter, setCurrentSorter] = useState(initialSorter);

  const fetchResources = useCallback(
    async (params = {}) => {
      try {
        setLoading(true);
        const newPagination = {
          current: params.current || currentPagination.current,
          pageSize: params.pageSize || currentPagination.pageSize,
        };
        const newSorter = {
          field: params.field || currentSorter.field,
          order: params.order || currentSorter.order,
        };

        setCurrentPagination(newPagination);
        setCurrentSorter(newSorter);

        const { data, total: newTotal } = await resourceService.getResources({
          page: newPagination.current,
          pageSize: newPagination.pageSize,
          orderBy: newSorter.field,
          ascending: newSorter.order === "ascend",
          type: type,
          ...(params?.search !== "" ? { searchQuery: params.search } : {}),
        });

        setResources(data || []);
        setTotal(newTotal || 0);

        return { data, total: newTotal };
      } catch (error) {
        console.error("获取列表失败:", error);
        message.error("获取列表失败");
      } finally {
        setLoading(false);
      }
    },
    [currentPagination, currentSorter]
  );

  const createResource = async (values) => {
    try {
      const newResource = await resourceService.createResource(values);
      await fetchResources({ current: 1 });
      message.success("创建成功");
      return newResource;
    } catch (error) {
      message.error("创建失败");
      throw error;
    }
  };

  const updateResource = async (id, values) => {
    try {
      const updatedResource = await resourceService.updateResource(id, values);
      await fetchResources({ current: currentPagination.current });
      message.success("更新成功");
      return updatedResource;
    } catch (error) {
      message.error("更新失败");
      throw error;
    }
  };

  const deleteResource = async (id) => {
    try {
      await resourceService.deleteResource(id, type);
      const newCurrent =
        resources.length === 1 && currentPagination.current > 1
          ? currentPagination.current - 1
          : currentPagination.current;
      await fetchResources({ current: newCurrent });
      message.success("删除成功");
    } catch (error) {
      message.error("删除失败");
      throw error;
    }
  };

  return {
    resources,
    loading,
    total,
    currentPagination,
    currentSorter,
    fetchResources,
    createResource,
    updateResource,
    deleteResource,
  };
};
