'use client';

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

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

export function EditUserClient() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const userId = Number(params.id);

  const { data: user, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => usersApi.get(userId),
    enabled: !!userId,
  });

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

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

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error || !user) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load user</div>
      </div>
    );
  }

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