import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { areaClient } from '../api/areaClient';
import type { CreateAreaRequest, UpdateAreaRequest, AreaQueryParams } from '../types/area';
import { toast } from 'sonner';

// 获取区域列表的hook
export const useAreas = (params?: AreaQueryParams) => {
  return useQuery({
    queryKey: ['areas', params],
    queryFn: async () => {
      const res = await areaClient.index.$get({
        query: {
          page: params?.page || 1,
          pageSize: params?.pageSize || 100,
          filters: params?.filters || '',
          sortBy: params?.sortBy || 'id',
          sortOrder: params?.sortOrder || 'ASC'
        }
      });
      if (res.status !== 200) throw new Error('获取区域列表失败');
      const response = await res.json();
      return response.data;
    },
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });
};

// 获取区域子树的hook
export const useAreaSubtree = (parentId: number) => {
  return useQuery({
    queryKey: ['areas-subtree', parentId],
    queryFn: async () => {
      const res = await areaClient.index.$get({
        query: {
          page: 1,
          pageSize: 100,
          filters: JSON.stringify({ parentId }),
          sortBy: 'id',
          sortOrder: 'ASC'
        }
      });
      if (res.status !== 200) throw new Error('获取区域子树失败');
      const response = await res.json();
      return response.data;
    },
    enabled: !!parentId,
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });
};

// 创建区域的hook
export const useCreateArea = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: CreateAreaRequest) => {
      const res = await areaClient.index.$post({ json: data });
      if (res.status !== 201) throw new Error('创建区域失败');
    },
    onSuccess: (_, variables) => {
      // 更新根级缓存
      queryClient.invalidateQueries({ queryKey: ['areas'] });
      queryClient.invalidateQueries({ queryKey: ['areas-tree-province'] });

      // 如果创建的是子节点，更新父节点的子树缓存
      if (variables.parentId) {
        queryClient.invalidateQueries({ queryKey: ['areas-subtree', variables.parentId] });
      }

      toast.success('区域创建成功');
    },
    onError: () => {
      toast.error('创建失败，请重试');
    }
  });
};

// 更新区域的hook
export const useUpdateArea = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, data }: { id: number; data: UpdateAreaRequest }) => {
      const res = await areaClient[':id'].$put({
        param: { id },
        json: data
      });
      if (res.status !== 200) throw new Error('更新区域失败');
    },
    onSuccess: () => {
      // 更新所有相关缓存
      queryClient.invalidateQueries({ queryKey: ['areas'] });
      queryClient.invalidateQueries({ queryKey: ['areas-tree-province'] });
      queryClient.invalidateQueries({ queryKey: ['areas-subtree'] });

      toast.success('区域更新成功');
    },
    onError: () => {
      toast.error('更新失败，请重试');
    }
  });
};

// 删除区域的hook
export const useDeleteArea = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: number) => {
      const res = await areaClient[':id'].$delete({
        param: { id }
      });
      if (res.status !== 204) throw new Error('删除区域失败');
    },
    onSuccess: () => {
      // 更新所有相关缓存
      queryClient.invalidateQueries({ queryKey: ['areas'] });
      queryClient.invalidateQueries({ queryKey: ['areas-tree-province'] });
      queryClient.invalidateQueries({ queryKey: ['areas-subtree'] });

      toast.success('区域删除成功');
    },
    onError: () => {
      toast.error('删除失败，请重试');
    }
  });
};

// 切换区域状态的hook
export const useToggleAreaStatus = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, isDisabled }: { id: number; isDisabled: number }) => {
      const res = await areaClient[':id'].$put({
        param: { id },
        json: { isDisabled }
      });
      if (res.status !== 200) throw new Error('更新区域状态失败');
    },
    onSuccess: () => {
      // 更新所有相关缓存
      queryClient.invalidateQueries({ queryKey: ['areas'] });
      queryClient.invalidateQueries({ queryKey: ['areas-tree-province'] });
      queryClient.invalidateQueries({ queryKey: ['areas-subtree'] });

      toast.success('区域状态更新成功');
    },
    onError: () => {
      toast.error('状态更新失败，请重试');
    }
  });
};