'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';

import { usersApi } from '@/lib/api';
import { UserForm, type UserFormData } from '@/components/users/user-form';
import type { CreateUserRequest } from '@/types/models';

export function NewUserClient() {
  const router = useRouter();
  const queryClient = useQueryClient();

  const createMutation = useMutation({
    mutationFn: (data: CreateUserRequest) => usersApi.create(data),
    onSuccess: (user) => {
      toast.success('User created successfully');
      queryClient.invalidateQueries({ queryKey: ['users'] });
      router.push(`/users/${user.id}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to create user');
    },
  });

  const handleSubmit = async (data: UserFormData) => {
    await createMutation.mutateAsync(data as unknown as CreateUserRequest);
  };

  return (
    <UserForm
      onSubmit={handleSubmit}
      isSubmitting={createMutation.isPending}
    />
  );
}
