import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { userService } from "../services/userService";
import {
  CreateUserRequest,
  UpdateUserRequest,
  PaginationParams,
} from "../services/types";
import { useToast } from "../contexts/ToastContext";
import { useLoading } from "../stores/useAppStore";

export const useUsers = (params?: PaginationParams) => {
  const { setLoading } = useLoading();

  return useQuery({
    queryKey: ["users", params],
    queryFn: async () => {
      setLoading("users", true);
      try {
        const mockUsers = userService.getMockUsers();

        let filteredUsers = mockUsers;

        if (params?.search) {
          filteredUsers = mockUsers.filter(
            (user) =>
              user.name.toLowerCase().includes(params.search!.toLowerCase()) ||
              user.email.toLowerCase().includes(params.search!.toLowerCase())
          );
        }

        if (params?.sortBy) {
          filteredUsers.sort((a, b) => {
            const aValue = a[params.sortBy as keyof typeof a];
            const bValue = b[params.sortBy as keyof typeof b];

            if (params.sortOrder === "desc") {
              return aValue < bValue ? 1 : -1;
            }
            return aValue > bValue ? 1 : -1;
          });
        }

        const page = params?.page || 1;
        const limit = params?.limit || 10;
        const startIndex = (page - 1) * limit;
        const paginatedUsers = filteredUsers.slice(
          startIndex,
          startIndex + limit
        );

        return {
          success: true,
          data: paginatedUsers,
          total: filteredUsers.length,
          page,
          limit,
        };
      } finally {
        setLoading("users", false);
      }
    },
    staleTime: 5 * 60 * 1000,
  });
};

export const useUser = (id: string) => {
  return useQuery({
    queryKey: ["user", id],
    queryFn: () => userService.getUser(id),
    enabled: !!id,
  });
};

export const useCreateUser = () => {
  const queryClient = useQueryClient();
  const toast = useToast();

  return useMutation({
    mutationFn: (userData: CreateUserRequest) =>
      userService.createUser(userData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["users"] });
      toast.success("کاربر با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      toast.error(error?.response?.data?.message || "خطا در ایجاد کاربر");
    },
  });
};

export const useUpdateUser = () => {
  const queryClient = useQueryClient();
  const toast = useToast();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateUserRequest }) =>
      userService.updateUser(id, data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ["users"] });
      queryClient.invalidateQueries({ queryKey: ["user", variables.id] });
      toast.success("کاربر با موفقیت ویرایش شد");
    },
    onError: (error: any) => {
      toast.error(error?.response?.data?.message || "خطا در ویرایش کاربر");
    },
  });
};

export const useDeleteUser = () => {
  const queryClient = useQueryClient();
  const toast = useToast();

  return useMutation({
    mutationFn: (id: string) => userService.deleteUser(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["users"] });
      toast.success("کاربر با موفقیت حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.response?.data?.message || "خطا در حذف کاربر");
    },
  });
};
